userMod2
userMod2

Reputation: 8990

JavaScript - Add an item to an object array depending on index

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

Upvotes: 0

Views: 63

Answers (5)

Fabiano Taioli
Fabiano Taioli

Reputation: 5540

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

Even more concise...

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

Upvotes: 1

Shubham Baranwal
Shubham Baranwal

Reputation: 2498

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

Upvotes: 0

Luís Ramalho
Luís Ramalho

Reputation: 10218

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

Upvotes: 0

KooiInc
KooiInc

Reputation: 122956

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

Upvotes: 1

kuzditomi
kuzditomi

Reputation: 730

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

Upvotes: 0

Related Questions