JavaScript-根据索引将项目添加到对象数组

时间:2020-04-17 07:03:05

标签: javascript

我有一个对象数组,可以使用theNewFieldToAdd向其中添加一个新属性(map),但是,我只想在索引为一定数量的情况下添加该属性。

有什么想法吗?

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

5 个答案:

答案 0 :(得分:1)

会做三元研究吗?

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

答案 1 :(得分:1)

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

更简洁...

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

答案 2 :(得分:0)

您不必简短。这样的逻辑可以使可读性得到回报。

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

   return row;
})

答案 3 :(得分:0)

尝试下面的工作演示-

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

答案 4 :(得分:0)

例如,您可以使用short-circuit evaluation使其更加简洁:

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

console.log(result);