根据条件,如何从处理后的数组中删除一个项目并将其移动到另一个数组?

问题描述 投票:0回答:4

我的反应组件中有两个数组,如下......

const [Selected, setSelected] = React.useState([]);
const [NonSelected, setNonSelected] = React.useState([]);

const Tmp_Selected = [
  { "Metric": "AAA", "Weight": 10, "Value": "xxx" },
  { "Metric": "BBB", "Weight": 20, "Value": "xx1" },
  { "Metric": "CCC", "Weight": 30, "Value": "xx2" },
];
const Tmp_NonSelected = [
  { "Metric": "DDD", "Weight": 5, "Value": "yy" },
  { "Metric": "EEE", "Weight": 15, "Value": "zz" },
  { "Metric": "FFF", "Weight": 25, "Value": "cc" },
];

React.useEffect(() => {
  setSelected(Tmp_Selected);
  setNonSelected(Tmp_NonSelected);
}, [location]);

有一个函数仅传递

Metric
Weight
相关值。基于此,我需要将符合两个条件的每个对象从
NonSelected
移动到
Selected
数组。

const MoveValues = (Metric='DDD', Weight=5) => {
  
}

上述两项默认措施的预期结果等于此...

const Tmp_Selected = [
   { "Metric": "AAA", "Weight": 10, "Value": "xxx" },
   { "Metric": "BBB", "Weight": 20, "Value": "xx1" },
   { "Metric": "CCC", "Weight": 30, "Value": "xx2" },
   { "Metric": "DDD", "Weight": 5, "Value": "yy" },
];
const Tmp_NonSelected = [
   { "Metric": "EEE", "Weight": 15, "Value": "zz" },
   { "Metric": "FFF", "Weight": 25, "Value": "cc" },
];
javascript arrays algorithm filter splice
4个回答
1
投票

OP 解决任务实际依赖的功能是数组变异

reject
功能。

这样的函数(或方法)确实接受类似于

filter
的回调,其中回调的参数为
item, idx, arr, ...
,并且其返回值预计为布尔类型或至少为 true/falsy。根据每次调用回调的结果,在完全迭代要操作的数组时,
reject
实现将
splice
操作数组中的每个匹配项,从而改变后者。每个拼接项都收集在实现的
result
数组中,这也是
reject
函数的返回值。

因此,OP

moveValues
功能的可能实现可以像这样简单地完成......

const tmpSelected = [
  { "Metric": "AAA", "Weight": 10, "Value": "xxx" },
  { "Metric": "BBB", "Weight": 20, "Value": "xx1" },
  { "Metric": "CCC", "Weight": 30, "Value": "xx2" },
];
const tmpNonSelected = [
  { "Metric": "DDD", "Weight": 5, "Value": "yy" },
  { "Metric": "EEE", "Weight": 15, "Value": "zz" },
  { "Metric": "FFF", "Weight": 25, "Value": "cc" },
];

const moveValues = (Metric, Weight) => {
  tmpSelected
    .push(
      ...reject(tmpNonSelected, item => {

        return item.Metric === Metric && item.Weight === Weight;
      }),
    );
};
moveValues('DDD', 5);

console.log({ tmpSelected, tmpNonSelected });
.as-console-wrapper { min-height: 100%!important; top: 0; }
<script>
function reject(target, condition) {
  const result = [];

  let idx = target.length;
  const copy = [...target];

  // - Processing the `target` array from RIGHT to LEFT
  //   keeps the `idx` always in sync with both related
  //   array items, the one of the mutated and also the
  //   one of the unmutated `copy` of the processed array
  //   reference.
  // - Thus, `condition` always gets passed the unmutated
  //   shallow `copy`.

  while (idx) {
    if (
      // - take a *sparse array* into account.
      target.hasOwnProperty(--idx) &&

      // - keep processing the unmutated array.
      condition(copy[idx], idx, copy)
    ) {
      // - keep filling the `result` array with each
      //   *rejected* item FROM its LEFT side while
      //   mutating the `target` array.
      result.unshift(target.splice(idx, 1)[0]);
    }
  }
  // - returns an array of rejected items, but not the
  //   processed and mutated `target` array reference.
  return result;
}
</script>


1
投票
const MoveValues = (Metric = 'DDD', Weight = 5) => {
      const item_Selected = NonSelected.find(item => item.Metric === Metric && item.Weight === Weight)
      const Tmp_Selected = [...Selected, item_Selected]
      const Tmp_NonSelected = NonSelected.filter(item => item.Metric !== Metric && item.Weight !== Weight)

      console.log(Tmp_NonSelected)
      console.log(Tmp_Selected)
}

1
投票

您可以使用Arrays的filter方法从nonSelected Array中删除对象。

  1. 找到要移动的物体
  2. 使用过滤器从非选定数组中删除对象
  3. 使用扩展运算符将对象添加到选定的数组中
  4. 两个对象的setState

const MoveValues = (Metric = 'DDD', Weight = 5) => {

    const objectToMove = NonSelected.find(object => object.Metric === Metric && object.Weight === Weight);
  
    if (objectToMove) {

      const arrayOfNonSelected = NonSelected.filter(obj => obj !== objectToMove);
  
      const arrayOfSelected = [...Selected, objectToMove];
  
      setNonSelected(arrayOfNonSelected);
      setSelected(updatedSelected);
    }

  }


1
投票

这是您的组件的完整代码:

    import React, { useEffect } from 'react'

function StackTest() {
    const [Selected, setSelected] = React.useState([]);
    const [NonSelected, setNonSelected] = React.useState([]);

    const Tmp_Selected = [
        { "Metric": "AAA", "Weight": 10, "Value": "xxx" },
        { "Metric": "BBB", "Weight": 20, "Value": "xx1" },
        { "Metric": "CCC", "Weight": 30, "Value": "xx2" },
    ];
    const Tmp_NonSelected = [
        { "Metric": "DDD", "Weight": 5, "Value": "yy" },
        { "Metric": "EEE", "Weight": 15, "Value": "zz" },
        { "Metric": "FFF", "Weight": 25, "Value": "cc" },
    ];
    useEffect(() => {
        setSelected(Tmp_Selected);
        setNonSelected(Tmp_NonSelected);
    }, []);

    const MoveValues = (Metric = '', Weight = 0) => {
        const objectToMove = NonSelected.find(object => object.Metric === Metric && object.Weight === Weight);
        // console.log(NonSelected.find(object => object.Metric === Metric && object.Weight === Weight),"objectToMove");
        if (objectToMove) {
            const arrNonSelected = NonSelected.filter(obj => obj !== objectToMove);
            const arrSelected = [...Selected, objectToMove];
            setNonSelected(arrNonSelected);
            setSelected(arrSelected);
        }
    }
    const MoveBackValues = (Metric = '', Weight = 0) => {
        const objectToMove = Selected.find(object => object.Metric === Metric && object.Weight === Weight);
        // console.log(Selected.find(object => object.Metric === Metric && object.Weight === Weight),"objectToMove");
        if (objectToMove) {
            const arrSelected = Selected.filter(obj => obj !== objectToMove);
            const arrNonSelected = [...NonSelected, objectToMove];
            setSelected(arrSelected);
            setNonSelected(arrNonSelected);
        }
    }

    return (
        <>
        <h1>Selected</h1>
        {Selected && Selected.map((item,index) => (
            <p key={index} onClick={(e) => {
                MoveBackValues(item.Metric, item.Weight)
            }
            }>
            {item.Metric} - {item.Value} - {item.Weight}
            <br/></p>
        ))}
        <h1>NonSelected</h1>
        {NonSelected && NonSelected.map((item,index) => (
            <p key={index} onClick={(e) => {
                MoveValues(item.Metric, item.Weight)
            }
            }>
            {item.Metric} - {item.Value} - {item.Weight}
            <br/></p>
        ))}
        </>
    )
}

export default StackTest
© www.soinside.com 2019 - 2024. All rights reserved.