簡體   English   中英

JavaScript - 根據索引將項目添加到 object 數組

[英]JavaScript - Add an item to an object array depending on index

我有一個 object 數組,我使用map添加一個新屬性( theNewFieldToAdd ),但是我只想在索引為某個數字時添加該屬性。

有任何想法嗎?

rows.map((row, index) => ({
   ...row,
   theNewFieldToAdd: true
})),

三元會起作用嗎?

 let x = [ {a: 1, b: 2}, {a: 3, b: 4}, {a: 5, b: 6}, {a: 7, b: 8} ]; console.log( x.map( (row, i) => (i > 2? {...row, newValue: true}: row) ) );
 .as-console-wrapper { top: 0; max-height: 100%;important; }

rows.map((row, index) => ({
   ...row,
   ...(index===MYINDEX ? {theNewFieldToAdd: true} : {})
}))

更簡潔...

rows.map((row, index) => ({
  ...row,
  ...index===MYINDEX && {theNewFieldToAdd: true}
}))

你不必縮短它。 像這樣的邏輯可以獲得可讀性。

rows.map((row, index) => {
   if(index === x){
     row.theNewField = true
   }

   return row;
})

試試下面的工作演示 -

 rows = [{'first': 1},{'second': 2},{'third': 3},{'fourth': 4},{'fifth': 5}]; rows1 = rows.map((row, index) => (index == 1? {...row, theNewFieldToAdd: true }: row)); console.log(rows1);

例如,您可以使用短路評估使其更簡潔:

 let rows = [{ key: "a" }, { key: "b" }, { key: "c" }]; let result = rows.map((row, index) => ({...row, ...(index === 0 && { theNewFieldToAdd: true }), })); console.log(result);

暫無
暫無

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

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