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

171
Visualizações
How to insert each array item into each object of other array?

I have 2 arrays

I want this:

[{name: 'Sweater', qty: 1}, {name: 'Skirt', qty: 3}, {name: 'Socks', qty: 2}]

but I get

    qtyList = [1, 3, 2]
    data = [{name: 'Sweater', qty: 1}, {name: 'Skirt', qty: 1}, {name: 'Socks', qty: 1}]

    let assignQty = data.map((x, id) => {
            qtyList.map((y, idx) => {
                if (idx == id) return x.qty = y
            })
        })
        console.log('assignQty', assignQty)

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

0

You're essentially zipping the 2 lists together - typically done as follows:

const qtyList = [1, 3, 2]
const data = [{name: 'Sweater', qty: 1}, {name: 'Skirt', qty: 1}, {name: 'Socks', qty: 1}]

const result = data.map((item,idx) => ({...item, qty: qtyList[idx]}))

console.log(result);

about 4 years ago · Juan Pablo Isaza Relatório

0

Without using the spread operator, update the required field and then return x.

    qtyList = [1, 3, 2]
    data = [{name: 'Sweater', qty: 1}, {name: 'Skirt', qty: 1}, {name: 'Socks', qty: 1}]

    var assignQty = data.map((x, id) => {x.qty=qtyList[id];return x;})

    console.log('assignQty', assignQty)

about 4 years ago · Juan Pablo Isaza Relatório

0

This is my approach to your question. In your example, you were trying to map two arrays into one. This approach "loops" the data array containing the objects you want to change.

Using the index of each object it sets the item.qty to the value in qtyList[index].

    qtyList = [1, 3, 2];
    data = [{
      name: 'Sweater',
      qty: 1
    }, {
      name: 'Skirt',
      qty: 1
    }, {
      name: 'Socks',
      qty: 1
    }];

    let assignQty = data.map((item, index) => {
      item.qty = qtyList[index];
      return item;
    });
    console.log(assignQty)

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