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

Add a new property to an object from an array of objects in Javascript

I am trying to add a new property to an object which is part of an array of objects.
The main array looks like this:

0: {key: 'Fruits', props: Array(22)}
1: {key: 'Dried', props: Array(1)}
2: {key: 'Fresh', props: Array(1)}
3: {key: 'Exotic', props: Array(6)}
4: {key: 'Nuts', props: Array(6)}

What I want to modify is an object inside props key. It is when clicking upon a certain object that matches the name that new property should be added. So my code looks like this:

    let updatedFruitsArr = [];
    const fruitsArr = [...getFruitsFromLocalStorge()];

    // modify the fruits array in order to add a new key to the 
    // object that matches the name selected
    fruitsArr.forEach((fruits) => {
        updatedFruitsArr.push({
            ...fruits,
            props: [...fruits.props].map((fruit) => {
                if (fruit.name === fruitName) {
                    return {
                        ...fruit,
                        isInCart: true
                    };
                } else {
                    return fruit
                }
            }),
        });
    });

However, every time updatedFruitsArr returns the original array without that property added.
Could you please tell me what I am doing wrong?
Thank you

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

>Solution :

You don’t need to create a new array and use .forEach and .push, you can just use .map:

const fruits = [
  {
    key: 'Fruits',
    props: [
      {
        name: 'Apple'
      },
      {
        name: 'Orange'
      },
      {
        name: 'Pear'
      }
    ]
  },
  {
    key: 'Nuts',
    props: [
      {
        name: 'Cashew'
      },
      {
        name: 'Peanuts'
      }
    ]
  }
];

const newFruits = fruits.map(fruitType => {
  return {
    ...fruitType,
    props: fruitType.props.map(fruit => {
      if(fruit.name === 'Apple'){
        return {
          ...fruit,
          isInCart: true
        }
      } else {
        return {
          ...fruit
        }
      }
    })
  }
});

console.log(newFruits);
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