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

110
Visualizações
How can I add an array item into another array

How do I add a value from one array into another array to create a new array?

I have two arrays and I want to filter through arrayTwo find where id === productID from arrayOne. Then add quantity from arrayOne to arrayTwo so I can get a result such as arrayThree

arrayOne = [
  {
   productID: "DuWTLdYkpwF1DJ2x8SGB",
   quantity: 2
  },
]
arrayTwo = [
{
  id: "DuWTLdYkpwF1DJ2x8SGB",
  minQuantity: 1,
  name: "5 Shade Palette",
  price: "950",
  size: "30g",
  unitPrice: 950,
  },
]

Wanted result::

arrayThree = [
{
  id: "DuWTLdYkpwF1DJ2x8SGB",
  minQuantity: 1,
  name: "5 Shade Palette",
  price: "950",
  size: "30g",
  unitPrice: 950,
  quantity: 2,
  },
]
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You can merge the two objects easily by using the spread operator:

arrayOne = [
  {
   productID: "DuWTLdYkpwF1DJ2x8SGB",
   quantity: 2
  },
]

arrayTwo = [
{
  id: "DuWTLdYkpwF1DJ2x8SGB",
  minQuantity: 1,
  name: "5 Shade Palette",
  price: "950",
  size: "30g",
  unitPrice: 950,
  },
]

console.log({...arrayOne[0], ...arrayTwo[0]})

Use this in combination with your initial filter and you should have what you want. However I would advise to use 'find()' instead.

This will look something like this:

// Loop every item of one array
arrayOne.forEach( (product) => {
  // Find linked product
  let productToMerge = arrayTwo.find(p => p.productID === product.productID)

 // Let's merge them
 let newItem = {...product, ...productToMerge}
})

Now it's just a matter of pushing this newItem in an array to collect all new items.

Spread

Find

about 4 years ago · Juan Pablo Isaza Relatório

0

Time complexity is O(n^2) here. If the given arrays are really long, not the best option. Basically: for each item in arrayOne, find its pair in arrayTwo and merge them.

let arrayThree = arrayOne.map(first => {
    return {
        ...first,
        ...arrayTwo.find(second => second.id == first.productID)
    }
});
about 4 years ago · Juan Pablo Isaza Relatório

0

Below is one possible way to achieve the target.

Code Snippet

// add "quantity" to existing products
const addDeltaToBase = (delta, base) => (
  // iterate over the "base" (ie, existing product array)
  base.map(
    ({ id, ...rest }) => {        // de-structure to access "id"
      // check if "id" is part of the delta (to update "quantity")
      const foundIt = delta.find(({ productID }) => productID === id);
      if (foundIt) {              // found a match, so update "quantity
        return ({
          id, ...rest, quantity: foundIt.quantity
        })
      };
      // control reaches here only when no match. Return existing data as-is
      return { id, ...rest }
    }
  )     // implicit return from "base.map()"
);

const arrayOne = [
  {
   productID: "DuWTLdYkpwF1DJ2x8SGB",
   quantity: 2
  },
];

const arrayTwo = [
{
  id: "DuWTLdYkpwF1DJ2x8SGB",
  minQuantity: 1,
  name: "5 Shade Palette",
  price: "950",
  size: "30g",
  unitPrice: 950,
  },
];

console.log(addDeltaToBase(arrayOne, arrayTwo));
.as-console-wrapper { max-height: 100% !important; top: 0 }

Explanation

Inline comments added in the snippet above.

NOTE

  • This answer will be able to handle both arrayOne & arrayTwo with multiple objects.
  • It matches the productId with the id and when matched, it merges the quantity into the output (ie, arrayThree).
  • It aims to be immutable so the input arrays may remain as-is
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