【问题标题】:How to filter array of object based on condition React JS如何根据条件 React JS 过滤对象数组
【发布时间】:2022-01-05 17:00:07
【问题描述】:

我是反应 js 的新手,我搜索了 google,对象追加,对象连接,浅拷贝,深拷贝在 JavaScript 中有,但是,我找不到将对象数组合并为单个数组对象。

如何根据类型过滤对象数组并将响应保存为单个对象数组?

    const options = ["Fruit", "Vegitables", "Drinks"];
        const mainArray=[{
        Type:'Fruit',
        Name:'apple',
        Amount:'20'
        },
        {
        Type:'Fruit',
        Name:'apple',
        Amount:'20'
        },
        {
        Type:'Vegitables',
        Name:'tomoto',
        Amount:'50'
        },
        {
        Type:'Vegitables',
        Name:'onion',
        Amount:'20'
        },
        {
        Type:'Drinks',
        Name:'Milk',
        Amount:'30'
        },
        {
        Type:'Drinks',
        Name:'Juice',
        Amount:'20'
        }
        ]
        ///Filtering By Type
        
        const filterByType=()=>{
        let allMergedData=[];
         selectedtypes?.map((type)=>{
            let mergedData=[];
            let filteredData= mainArray?.filter(x=>x.Type===type.toLowerCase());
            mergedData=[...filteredData];
            allMergedData=[...mergedData, ...filteredData];
         })
         return allMergedData;
        };
        
        return(
        <div>
        {options.map((option) => (
                    <MenuItem key={option} value={name}>
                      <Checkbox value={option}
                  onChange={handleChange}
                  checked={selected.includes(option)} />
                      <ListItemText primary={option} />
                    </MenuItem>
                  ))}
        </div>
        )

异常输出:


    allMergedData:[{
            Type:'Fruit',
            Name:'apple',
            Amount:'20'
            },
            {
            Type:'Fruit',
            Name:'apple',
            Amount:'20'
            },
            {
            Type:'Vegitables',
            Name:'tomoto',
            Amount:'50'
            },
            {
            Type:'Vegitables',
            Name:'onion',
            Amount:'20'
            },]

```

【问题讨论】:

  • 你为什么期望这个输出?请您分享您尝试的minimal reproducible example 吗?
  • 我需要将数据绑定到数据表中
  • 尝试使用“纯函数”。您的 filterByType() 函数正在使用外部定义的变量,这很危险。另外,检查您的预期输出,我认为它是否需要“饮料”类型?因为在选项数组上。
  • 我正在分享 CodeSandBox 链接。我在代码沙箱中添加了代码。 codesandbox.io/s/react-data-table-forked-090e9?file=/src/…
  • 我在控制台日志中得到了输出。我需要合并单个对象数组的三个对象。

标签: javascript arrays reactjs


【解决方案1】:

也许这个功能会有所帮助,根据您的需要进行编辑:

function groupBy(arr, criteria) {
  const newObj = arr.reduce(function (acc, currentValue) {
    if (!acc[currentValue[criteria]]) {
      acc[currentValue[criteria]] = [];
    }
    acc[currentValue[criteria]].push(currentValue);
    return acc;
  }, {});
  return newObj;
}

在这里测试一下:

https://jsfiddle.net/pmiranda/y9odgtjm/2/

【讨论】:

  • 好的,我试试这个。
猜你喜欢
  • 2020-05-25
  • 1970-01-01
  • 2018-10-04
  • 2023-01-26
  • 2019-09-15
  • 1970-01-01
  • 2019-04-05
  • 2022-01-19
  • 2020-12-14
相关资源
最近更新 更多