Home > Software design >  Can I assign a copy of an array of objects and add to those objects at the same time?
Can I assign a copy of an array of objects and add to those objects at the same time?

Time:09-15

Say I have an array of objects:

const myArr = [
    {name: 'one'},
    {name: 'two'}
]

If I wanted to use this array of object as a base and add a custom property to the objects for each use case I might have, could I assign the array to a new variable and also change the contents of its objects at the same time?

I know this can be done in 2 steps, but I'm wondering if it's possible to do it all at once?

For example:

const copyArr = myArr;
copyArr.forEach(obj => obj.newProp = 'some-new-prop');

This would now be

[
    {name: 'one', newProp: 'some-new-prop'},
    {name: 'two', newProp: 'some-new-prop'}
]

CodePudding user response:

You can use Array.map to iterate over each item and modify them. Note that map will not modify your original array and therefore is immutable.

const myArr = [{ name: "one" }, { name: "two" }];

const copyArr = myArr.map((item) => ({
  ...item,
  newProps: "some-new-prop",
}));

// [ { name: 'one', newProps: 'some-new-prop' },
//   { name: 'two', newProps: 'some-new-prop' } ]

  • Related