0

I have an object array to which I'm add a new property (theNewFieldToAdd) using map, however I only want to add the property if the index is of a certain number.

Any ideas?

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

5 Answers 5

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

Even more concise...

rows.map((row, index) => ({
  ...row,
  ...index===MYINDEX && {theNewFieldToAdd: true}
}))
Sign up to request clarification or add additional context in comments.

Comments

1

Would a ternary work?

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

Comments

0

you don't have to make it short. logics like this can pay off to be readable.

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

   return row;
})

Comments

0

You can use for example the short-circuit evaluation to make it a bit more concise:

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

console.log(result);

Comments

0

Try below working demo-

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.