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

144
Vistas
Adding a new property to an existing array of objects

I am using Formik within my React app and have the following initial values, which is just a portion of it:

"myInfo": [
            {
                "myId": 0,
                "myName": "Name A",
                "defaultVal": 2
            },
            {
                "myId": 1,
                "myName": "Name B",
                "defaultVal": 4
            }
]

What I am attempting to do is to try and add a new property to this array of objects but not having much luck.

My code is as follows:

const getAdditionalData = async (id, idx) => {
  try {
    const response = await fetch(`http://localhost:3000/more-data/${id}`);
    const myData = await response.json();

    myInfo[idx].vals = myData;
  } catch (err) {
    console.error(err.message);
  }
};        

useEffect(() => {
  myInfo.map((info, index) => {
    getAdditionalData(info.myId, index)
  });
}, []); 

FYI, the values returned in myData is another array of objects that looks like this:

when myId = 0 it returns:

[{id: 1, name: 'AA'}
 {id: 2, name: 'BB'}]

when myId = 1 it returns:

[{id: 3, name: 'CC'}
 {id: 4, name: 'DD'}
 {id: 5, name: 'EE'}]

What I am attempting to do is that while within the array loop, I want to add a new property within myInfo array. I tried the following, which didn't work:

myInfo[idx].vals = myData;

The end result that I am after is the following:

"myInfo": [
            {
                "myId": 0,
                "myName": "Name A",
                "defaultVal": 2,
                "vals": [
                   {id: 1, name: 'AA'},
                   {id: 2, name: 'BB'}
                ]
            },
            {
                "myId": 1,
                "myName": "Name B",
                "defaultVal": 4,
                "vals": [
                   {id: 3, name: 'CC'},
                   {id: 4, name: 'DD'},
                   {id: 5, name: 'EE'}
                ]
            }
]

You will see that a new property of vals has been added.

Any help would be much appreciated as not sure what I am missing.

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

It looks like you are attempting to use JSON strings like objects. They have to be parsed first.

See the following example.

const myInfo = `[
  {
    "myId": 0,
    "myName": "Name A",
    "defaultVal": 2
  },
  {
    "myId": 1,
    "myName": "Name B",
    "defaultVal": 4
  }
]`;

const myData = `[
  {"id": 3, "name": "CC"},
  {"id": 4, "name": "DD"},
  {"id": 5, "name": "EE"}
]`;

const parsedInfo = JSON.parse(myInfo);
const parsedData = JSON.parse(myData);

parsedInfo[0].vals = parsedData;

console.log(parsedInfo[0]);
about 4 years ago · Juan Pablo Isaza Denunciar

0

What is myInfo? A state, class or ref variable? Also take into consideration that map returns a brand new array so it doesn't mutate.

You can try this and you should see the updated array in myNewInfo:

useEffect(() => {
  const myNewInfo = myInfo.map((info, index) => ({
    ...info,
    vals: getAdditionalData(info.myId, index)
  }));
}, []);
about 4 years ago · Juan Pablo Isaza Denunciar

0

Here's what worked from me in native javascript:

const getAdditionalData = async () => {
  try {
    const response = await fetch(`http://localhost:5500/data.json`);
    const myData = await response.json();
    let newObj = [];
    myData.myInfo.map((data, i) => {
      newObj = [...newObj, { ...data, val: [...valObj[i]] }];
    });
    console.dir(newObj);
  } catch (err) {
    console.error(err.message);
  }
};

const valObj = [
  [
    { id: 1, name: "AA" },
    { id: 2, name: "BB" },
  ],
  [
    { id: 3, name: "CC" },
    { id: 4, name: "DD" },
    { id: 5, name: "EE" },
  ],
];

getAdditionalData();


//data.json

{
  "myInfo": [
    {
      "myId": 0,
      "myName": "Name A",
      "defaultVal": 2
    },
    {
      "myId": 1,
      "myName": "Name B",
      "defaultVal": 4
    }
  ]
}

Note that you would need to sync the indices of myInfo and valObj.

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