gpt4 book ai didi

javascript - 根据现有对象数组的几个属性返回新的对象数组

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:39:36 25 4
gpt4 key购买 nike

我正在努力思考如何实现我需要的东西。我的初始对象数组是 70k 个对象,每个对象有 15 个属性。通过过滤和映射,我将数据集归结为我认为相关的部分。我需要根据每个对象的 4 个属性中的每一个返回一个新的对象数组,它们是重复的 id's和不同levels对于每个 code .我过滤后的数据看起来像这样。

const arr = [{id: "12345", level: "1", current: "Y", code: "1"}, 
{id: "12345", level: "0", current: "N", code: "1"},
{id: "54321", level: "1", current: "N", code: "201"},
{id: "54321", level: "2", current: "Y", code: "201"},
{id: "54321", level: "3", current: "N", code: "201"},
{id: "54321", level: "0", current: "Y", code: "401"},
{id: "54321", level: "1", current: "N", code: "401"},
{id: "54321", level: "3", current: "N", code: "201"},
{id: "54321", level: "0", current: "N", code: "301"},
{id: "121212", level: "0", current: "N", code: "3"},
{id: "121212", level: "1", current: "N", code: "3"}]

我需要实现的是每个 id对于任何 currentY对于每个 code ,我需要找到最大值 level为此code .因此,对于上面的示例,结果输出将是一个对象数组,如下所示:

const result = [{id: "12345", max: "1", code: "1"}, 
{id: "54321", max: "3", code: "201"},
{id: "54321", max: "1", code: "401"}]

我什至不确定我想要的东西是否可行,或者我是否以错误的方式思考它。我整个上午都在绞尽脑汁想找出解决办法。

最佳答案

您可以使用 .filter().map() 根据 Y 获取初始值,然后使用 .reduce () 获取最大值:

const arr = [{id: "12345", level: "1", current: "Y", code: "1"}, 
{id: "12345", level: "0", current: "N", code: "1"},
{id: "54321", level: "1", current: "N", code: "201"},
{id: "54321", level: "2", current: "Y", code: "201"},
{id: "54321", level: "3", current: "N", code: "201"},
{id: "54321", level: "0", current: "Y", code: "401"},
{id: "54321", level: "1", current: "N", code: "401"},
{id: "54321", level: "3", current: "N", code: "201"},
{id: "54321", level: "0", current: "N", code: "301"},
{id: "121212", level: "0", current: "N", code: "3"},
{id: "121212", level: "1", current: "N", code: "3"}]

let initialValues = arr.filter(x => x.current === "Y")
.map(x => ({ id: x.id, max: x.level, code: x.code }));

let result = arr.reduce((result,current) => {
var value = result.find(x => x.id === current.id && x.code === current.code);
if(!value) return result;
if(value.max < current.level) {
value.max = current.level;
}
return result;
}, initialValues);

console.log(result);

关于javascript - 根据现有对象数组的几个属性返回新的对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51772650/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com