Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

107
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda