簡體   English   中英

使用 .filter 和 .forEach 時修改數組

[英]Modify array in place while using .filter and .forEach

我想過濾一組對象並更新過濾條目上的一些值。 這是我的原始代碼,沒有過濾:

let obj = {
  foo: [
    {
      bar: "I should be modified",
      modify: true,
    },{
      bar: "I should not be modified",
      modify: false,
    },{
      bar: "I should be modified",
      modify: true,
    },
  ],
};

obj.foo.forEach((item, i) => {
  let newItem = Object.assign({}, item);
  newItem.bar = "I have been modified";
  obj.foo[i] = newItem;
});

console.log(obj.foo);
/* Output:
  [
    {
      bar: "I have been modified",
      modify: true,
    },{
      bar: "I have been modified",
      modify: false,
    },{
      bar: "I have been modified",
      modify: true,
    },
  ],
*/

現在我想將.forEach(...替換為.filter(e => e.modify).forEach(... 。所以不是修改obj.foo所有元素, obj.foomodify === true那些帶有modify === true被修改。如何在 forEach 循環內不再次過濾的情況下做到這一點?

obj.foo.filter(e => e.modify).forEach((item, i) => {
  let newItem = Object.assign({}, item);
  newItem.bar = "I have been modified";
  obj.foo[i] = newItem; // will not work as the index i is not correct from the original array
});

console.log(obj.foo);

/* Expected output:
  [
    {
      bar: "I have been modified",
      modify: true,
    },{
      bar: "I should not be modified",
      modify: false,
    },{
      bar: "I have been modified",
      modify: true,
    },
  ],
*/

/* Actual output:
  [
    {
      bar: "I have been modified",
      modify: true,
    },{
      bar: "I have been modified",
      modify: true,
    },{
      bar: "I should be modified",
      modify: true,
    },
  ],
*/

 let obj = { foo: [ { bar: "baz", modify: true, },{ bar: "bad", modify: false, },{ bar: "hello", modify: true, }, ], }; const {foo} = obj; const t = foo.reduce((acc, curr) => { if (curr.modify) { curr.bar = "I have been modified"; acc.push(curr); } return acc; }, []); console.log(t)

這也可以這樣做:

obj.foo.filter(e => e.modify).map((item) => {
  item.bar = "I have been modified"
});

我認為這應該有所幫助。

因此,在閱讀完所有評論后,您不希望在其中使用 if 語句和其他內容,然后我想到了這個想法,無需更改太多代碼,為什么不讓每個項目都擁有自己的原始索引,修改后,刪除idx屬性:

 let obj = { foo: [ { bar: "I should be modified", modify: true, },{ bar: "I should not be modified", modify: false, },{ bar: "I should be modified", modify: true, }, ], }; let index = 0; obj.foo.filter(e => ++index && e.modify && (e.idx = index)).forEach((item, i) => { let newItem = Object.assign({}, item); newItem.bar = "I have been modified"; obj.foo[newItem.idx - 1] = newItem; delete newItem.idx; }); console.log(obj.foo);

暫無
暫無

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

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