1

With an object I can clone & add like:

   let newObject = {
      ...obj,
      [key]: { 
         ...obj[key],
         thing: true }
   }

So, this adds some objects to an array, then one object's property is updated. I know the item's index to update, but don't want to override existing properties.

Now I want to do the same for array:

   let newArray = [
     ...arr,
     [key]: { 
         ...arr[key],
         thing: true }
   ]

Which might do the same as above.

But that doesn't work.

Should {key}:thing work? I remember reading this somewhere, maybe its ES7?

I could do:

   let newArray = arr.map((item, key) => key === index ? { ...item, thing: true } : item);
 

But I was hoping for a cleaner syntax. I'll accept no if there is no similar syntax.

TrySpace
  • 2,233
  • 8
  • 35
  • 62

2 Answers2

2

You can use Object.assign():

const arr = [{ a: 1 }, { b: 1 }, { c: 1 }];
const index = 1;

const newArr = Object.assign([], arr, { [index]: { ...arr[index], thing: true } });
console.log(newArr);
Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177
0

Arrays don't have keys, so the syntax you are using doesn't work. Is it an array of objects? If so...

EDIT - based on your comment, try this:

// if you know the index of the object you'd like to modify
let newArray = [
     ...arr
]
newArray[idx][key] = thing

// if you don't know the index
let newArray = [
     ...arr
]
newArray.map((el) => {
    if (/* YOUR LOGIC HERE TO DETERMINE IF THIS IS THE OBJECT TO MODIFY! */) {
        return el[key] = thing
    } else {
        return el
    }
})

// if you want it done in one function...
let newArray = []
arr.map((el) => {
    if (el[key]) {
        newArray.push(Object.assign({}, { [key]: thing }))
        return el
    } else {
        newArray.push(Object.assign({}, el))
        return el
    }
})
Adam
  • 3,142
  • 4
  • 29
  • 48
  • I need to access a specific object's index in the array, and only update that one's property, after it has been inserted into the new array. – TrySpace Jun 12 '17 at 18:10
  • I'm sure that OP knows that this can be done this way, but I think they're looking for a one-line (i.e. a single expression) solution. – Michał Perłakowski Jun 12 '17 at 18:27
  • @TrySpace, I don't think it can be done in one, succinct function. You need to do too many things: 1) copy an arry; 2) check each elem of the array to see if it matches some object you desire; 3) modify the desired elem. The best I can think of is the 3rd example I give in my code, above. – Adam Jun 12 '17 at 19:12