Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

141
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda