简体   繁体   English

如何将数组项添加到另一个数组中

[英]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 .我有两个 arrays,我想通过 arrayTwo 进行过滤,从arrayOne中找到id === productID位置 Then add quantity from arrayOne to arrayTwo so I can get a result such as arrayThree然后将arrayOne中的quantity添加到arrayTwo ,这样我就可以获得诸如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,
  },
]

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.但是我建议改用“find()”。

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.现在只需将这个 newItem 推入数组即可收集所有新项目。

Spread 传播

Find 寻找

Time complexity is O(n^2) here.这里的时间复杂度是 O(n^2)。 If the given arrays are really long, not the best option.如果给定的 arrays 真的很长,则不是最佳选择。 Basically: for each item in arrayOne , find its pair in arrayTwo and merge them.基本上:对于arrayTwo中的每个项目,在arrayOne中找到它的对并合并它们。

let arrayThree = arrayOne.map(first => {
    return {
        ...first,
        ...arrayTwo.find(second => second.id == first.productID)
    }
});

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.这个答案将能够处理具有多个对象的arrayOnearrayTwo
  • It matches the productId with the id and when matched, it merges the quantity into the output (ie, arrayThree ).它将productIdid匹配,当匹配时,它将quantity合并到 output(即arrayThree )中。
  • It aims to be immutable so the input arrays may remain as-is它旨在保持不变,因此输入 arrays 可能保持原样

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM