简体   繁体   中英

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

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

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

Even more concise...

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM