Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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'}
]

>Solution :

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' } ]

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading