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

175
Visualizações
How to properly append array of element to array of object

I have these array and array of objects in my React code:

var A = [
  {id: 1, name: "han"},
  {id: 2, name: "mohd"},
]

var B = [100, 200];

and I want to append B to A, so that the output becomes something like this:

var A = [
  {id: 1, name: "han", score: "100"},
  {id: 2, name: "mohd", score: "200},
]

I tried doing it with the code below:

var newArray = [];

for (let k = 0; k < A.length; k++) {
        newArray = B.map(score => ({...A[k], score}));
}

return newArray;

However, the code above returns this output when console logged:

newArray = [
  {id: 2, name: "mohd", score: "100"},
  {id: 2, name: "mohd", score: "200},
]

It only appends the elements to the latest object, instead of to all objects. Anyone knows what is wrong with my code? Thank you!

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

If you're going to use map you don't also need a loop since map will iterate over the array of objects, and return new array with new objects containing the score property.

Use the second parameter of the callback - the index - to identify which element of b we should be adding as the score.

const a = [
  {id: 1, name: 'han'},
  {id: 2, name: 'mohd'},
];

const b = [100, 200];

// `map` over `a` making sure we get the object
// in each iteration as well as its index
const out = a.map((obj, i) => {

  // Create a new object adding in the
  // new `score` property using the element in `b`
  // that matches the index
  return { ...obj, score: b[i] };

});

console.log(out);

about 4 years ago · Juan Pablo Isaza Relatório

0

Try something like this

const C = A.map((value, idx) =>({
   ...value,
   score: B[idx],
 }));

console.log(C)
about 4 years ago · Juan Pablo Isaza Relatório

0

If your both array lenght Will same then use this method

 var A = [
      {id: 1, name: "han"},
      {id: 2, name: "mohd"},
    ]
    
    var B = [100, 200];
    console.log(A.map((x,i)=>
        {return {
            ...x,
        score:B[i]
        }
        }
                     ))

If not sure About use this eg..

var A = [
  {id: 1, name: "han"},
  {id: 2, name: "mohd"},
   {id: 2, name: "mohd"},
]

var B = [100, 200];
console.log(A.map((x,i)=>
    {return {
        ...x,
    score:!B[i]?0:B[i]
    }
    }
                 ))
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