代码之家  ›  专栏  ›  技术社区  ›  Jack Venevankham

如何将数组的特定值复制到Javascript中的另一个数组?

  •  0
  • Jack Venevankham  · 技术社区  · 2 年前

    const arr1 = [
        {id: 1, qty: 2, checked: true},
        {id: 2, qty: 2, checked: true},
        {id: 3, qty: 2, checked: false}
    ]
    
    const arr2 = [
        {id: 1, qty: 2},
        {id: 2, qty: 2}
    ]
    

    我要复制的值 arr1 arr2 哪里 checked true arr1 值已存在于中 arr2 我只想让它更新它的 qty duplicate 再一次但我的问题是,在某些情况下,我会同时复制和更新它。下面我尝试使用for循环。

    const handleAdd = () => {
        let newArray = [...arr2]
        for (let i = 0; i < arr1.length; i++) {
            for (let j = 0; j < arr2.length; j++) {
                if(arr2[j].id === arr1[i].id && arr1[i].checked === true){
                    newArray[j].qty = newArray[j].qty + arr1[i].qty
                    break
                }else{
                    if(arr1[i].checked === true){
                        newArray.push(arr1[i])
                        break
                    }
                }
            }
        }
        console.log(newArray)
    }
    

    这里出了什么问题,有什么解决方案吗?提前感谢

    2 回复  |  直到 2 年前
        1
  •  2
  •   CertainPerformance    2 年前

    在这里:

    }else {
        if (arr1[i].checked === true) {
            newArray.push(arr1[i])
            break
    

    你正在努力 newArray 如果选中项目 在一路迭代之前 第二个数组。如果选中了第一个数组的项,那么无论第二个数组中有什么,都只会选中其中的内容 arr2[0] 在打断其中一个分支之前-这会把你的逻辑搞砸。

    首先按ID将第二个数组分组如何?一眼就能看出它更有意义,还可以降低计算复杂度。

    const arr1 = [
        {id: 1, qty: 2, checked: true},
        {id: 2, qty: 2, checked: true},
        {id: 3, qty: 2, checked: false}
    ]
    
    const arr2 = [
        {id: 1, qty: 2},
        {id: 2, qty: 2}
    ]
    const handleAdd = () => {
        const qtyById = Object.fromEntries(
          arr2.map(({ id, qty }) => [id, qty])
        );
        for (const item of arr1) {
          if (item.checked) {
            qtyById[item.id] = (qtyById[item.id] || 0) + item.qty;
          }
        }
        const newArray = Object.entries(qtyById).map(([id, qty]) => ({ id, qty }));
        console.log(newArray)
    }
    
    handleAdd();

    如果 arr2

        2
  •  1
  •   jsN00b    2 年前

    下面介绍的是实现预期目标的一种可能方法。

    代码段

    const myAdd = (needle, hayStack) => (
      hayStack.map(
        ({id, qty}) => ({
          id, qty,
          ...(
            needle.some(n => n.checked && n.id === id)
            ? (
              { qty } = needle.find(n => n.checked && n.id === id),
              { qty }
            )
            : {}
          )
        })
      ).concat(
        needle
        .filter(
          ({ id, checked }) => checked && !hayStack.some(h => h.id === id)
        ).map(({ id, qty }) => ({ id, qty }))
      )
    );
    /* explanation
    // method to add or update arr2
    const myAdd = (needle, hayStack) => (
      // first iterate over "arr2" (called hayStack here)
      // and update each item by matching "id" when "arr1" (called needle here)
      // has "checked" true
      hayStack.map(
        // de-structure "arr2" to directly access "id" and "qty"
        ({id, qty}) => ({
          id, qty,        // by default populate both "id" and "qty"
          ...(            // if "arr1" has a matching "id" and "checked" is true
                          // then, ".find()" the particular elt and 
                          // update the "qty"
            needle.some(n => n.checked && n.id === id)
            ? (           // extract only the "qty" from result ".find()"
              { qty } = needle.find(n => n.checked && n.id === id),
              { qty }     // return an object with one prop "qty"
            )
            : {}          // if "arr1" has no matching "id", no change to "arr2" elt
          )
        })
      ).concat(
        // concat items in "arr1" which are not already present in "arr2"
        // and have "checked" as "true"
        needle
        .filter(      // first filter only "new" items
          ({ id, checked }) => checked && !hayStack.some(h => h.id === id)
        ).map(        // destructure to extract only "id" and "qty" props
          ({ id, qty }) => ({ id, qty })
        )
      )
    );
    */
    const arr1 = [
        {id: 1, qty: 3, checked: true},
        {id: 2, qty: 2, checked: true},
        {id: 3, qty: 2, checked: false},
        {id: 4, qty: 4, checked: true}
    ];
    
    const arr2 = [
        {id: 1, qty: 2},
        {id: 2, qty: 2}
    ];
    
    console.log(
      'add/update elements from arr1:\n',
      JSON.stringify(arr1),
      '\n\ninto arr2: ',
      JSON.stringify(arr2),
      '\n\n',
      myAdd(arr1, arr2)
    );
    .as-console-wrapper { max-height: 100% !important; top: 0 }

    添加到上述代码段的内联注释。