Modify object property in an array of objects

后端 未结 11 1117
抹茶落季
抹茶落季 2020-11-29 07:09
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);
<         


        
相关标签:
11条回答
  • 2020-11-29 07:31

    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);

    0 讨论(0)
  • 2020-11-29 07:34

    Without jQuery and backwards compatibility

    for (var i = 0; i < foo.length; i++) {
        if (foo[i].bar === 1) {
            foo[i].baz = [11,12,13];
        }
    }
    
    0 讨论(0)
  • 2020-11-29 07:36
    $.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
    }
    }
    
    0 讨论(0)
  • 2020-11-29 07:39

    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);

    0 讨论(0)
  • 2020-11-29 07:39

    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;
       }
     })
    
    0 讨论(0)
  • 2020-11-29 07:41

    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;
        }
    
    0 讨论(0)
提交回复
热议问题