Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

106
Views
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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!