簡體   English   中英

修改對象數組中的 object 屬性

[英]Modify object property in an array of objects

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

http://jsfiddle.net/98EsQ/

有沒有什么方法可以在不創建新的 arrays 和/或對象的情況下修改某個對象屬性(比如我在上面過濾掉的屬性)?

期望的結果: [{ bar: 1, baz: [11,22,33] }, { bar: 2, baz: [4,5,6] }]

當然,只需更改它:

使用 jQuery 的$.each

$.each(foo, function() {
    if (this.bar === 1) {
        this.baz[0] = 11;
        this.baz[1] = 22;
        this.baz[2] = 33;
        // Or: `this.baz = [11, 22, 33];`
    }
});

使用 ES5 的forEach

foo.forEach(function(obj) {
    if (obj.bar === 1) {
        obj.baz[0] = 11;
        obj.baz[1] = 22;
        obj.baz[2] = 33;
        // Or: `obj.baz = [11, 22, 33];`
    }
});

...或者您在這個其他 SO 答案中其他循環選項

.map展開( ... ) 運算符

var result = foo.map(el => el.bar == 1 ? {...el, baz: [11,22,33]} : el);

您可以使用find和更改其屬性。

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

我們也可以通過使用 Array 的 map 函數來實現:

 foo.map((obj) => {
   if(obj.bar == 1){
     obj.baz[0] = 11;
     obj.baz[1] = 22;
     obj.baz[2] = 33;
   }
 })

沒有 jQuery 和向后兼容性

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

});

但是 for 循環比 $.each 快,所以你可以嘗試使用

for(var i=0; i <foo.length; i++)
{

if(foo[i].bar==1)
{
//change the code
}
}
    const objArr = [
        {prop1: 'value1', prop2: 'value11'},
        {prop1: 'value2', prop2: 'value22'},
        {prop1: 'value3', prop2: 'option33'},
        {prop1: 'value4', prop2: 'option44'}
    ]

    const newObjArr = objArr.map(obj => {
            if (['value1', 'value2'].includes(obj.prop1)) {
                return {...obj, prop1: 'newValue'}
            }
            return obj
        }
    )
    
    // const responseGotten = [
    //     { prop1: 'newValue', prop2: 'value11' },
    //     { prop1: 'newValue', prop2: 'value22' },
    //     { prop1: 'value3', prop2: 'option33' },
    //     { prop1: 'value4', prop2: 'option44' }
    // ]

但在選擇任何提到的技術之前,請記住與每種方法相關的性能挑戰。

Object iterate For-In, average: ~240 microseconds.

Object iterate Keys For Each, average: ~294 microseconds.

Object iterate Entries For-Of, average: ~535 microseconds.

參考 - 你應該停止做的 3 個 JavaScript 性能錯誤

您可以利用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);

您可以使用簡單的 for 循環修改數組

 var foo = [{ bar: 1, baz: [1,2,3] }, { bar: 2, baz: [4,5,6] }]; for(i = 0;i < foo.length;i++){ //Here your confition for which item you went to edit if(foo[i].bar == 1){ //Here you logic for update property foo[i].baz= [1,11,22] } } console.log(foo);

你可以玩:

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

編輯

避免索引更改:

const markCompleted = (tasks, task) => {
      const index = tasks.findIndex(t => t.id === task.id);
      tasks[index] = task;
      return tasks;
    }
let myArray = [
{ id: 1, body: "wash dishes", state: "done" },
{ id: 2, body: "wash car", state: "onGoing" },
{ id: 3, body: "wash hands", state: "done" },
]

myArray.findIndex(function(obj){  //it will search between every object in array
    if (obj.body=="wash car"){ //find the object you looking for and pass to obj
        obj.state = "done"   // you can select and update any part you want here
    }

console.log(myArray) // see the updatet array

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM