var foo = [{ bar: 1, baz: [1,2,3] }, { bar: 2, baz: [4,5,6] }];
var filtered = $.grep(foo, function(v){
return v.bar === 1;
});
console.log(filtered);
<
You can make use of filter function of javascript.
obj = [
{inActive:false, id:1},
{inActive:false, id:2},
{inActive:false, id: 3}
];
let nObj = obj.filter(ele => {
ele.inActive = true;
return ele;
});
console.log(nObj);
Without jQuery and backwards compatibility
for (var i = 0; i < foo.length; i++) {
if (foo[i].bar === 1) {
foo[i].baz = [11,12,13];
}
}
$.each(foo,function(index,value)
{
if(this.bar==1)
{
this.baz[0] = 11;
this.baz[1] = 22;
this.baz[2] = 33;
}
});
but for loop is faster than $.each so u can try to use
for(var i=0; i <foo.length; i++)
{
if(foo[i].bar==1)
{
//change the code
}
}
You can use find and change its property.
let foo = [{ bar: 1, baz: [1,2,3] }, { bar: 2, baz: [4,5,6] }];
let obj = foo.find(f=>f.bar==1);
if(obj)
obj.baz=[2,3,4];
console.log(foo);
We can also achieve this by using Array's map function:
foo.map((obj) => {
if(obj.bar == 1){
obj.baz[0] = 11;
obj.baz[1] = 22;
obj.baz[2] = 33;
}
})
you can play around:
const tasks = [ { id: 1, done: false }, { id: 2, done: false } ]
const completed_task = { id: 1, done: true }
const markCompleted = (tasks, task) => {
const index = tasks.findIndex(t => t.id === task.id);
tasks.splice(index, 1);
tasks.push(task);
return tasks;
}
console.log(tasks)
console.log(markCompleted(tasks, completed_task))
EDIT
to avoid index change:
const markCompleted = (tasks, task) => {
const index = tasks.findIndex(t => t.id === task.id);
tasks[index] = task;
return tasks;
}