javascriptarraysobjectspread-syntaxmutability

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


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