gpt4 book ai didi

javascript - 如何从 JSON 对象数组中对 JSON 对象进行分组?

转载 作者:行者123 更新时间:2023-12-02 22:28:36 24 4
gpt4 key购买 nike

这是一个 JSON 对象数组,其中包含我想要分组的数组值(提取唯一值):

let myArray = [
{
"_id": "1",
"subdata": [
{
"subid": "11",
"name": "A"
},
{
"subid": "12",
"name": "B"
}
]
},
{
"_id": "2",
"subdata": [
{
"subid": "12",
"name": "B"
},
{
"subid": "33",
"name": "E"
}
]
}
]

最后我需要得到:

[
{
"subid": "11",
"name": "A"
},
{
"subid": "12",
"name": "B"
},
{
"subid": "33",
"name": "E"
}
]

我尝试过 lodash 但没有成功:

let newArray = lodash.uniqBy(lodash.concat(myArray, 'subdata.subid'), '_id');

当然,我可以一一扫描每个数组元素,但我认为使用 lodash 有简单的方法来做到这一点

最佳答案

使用_.flatMap()获取所有subdata项的数组,然后使用_.uniqueBy()subid:

const myArray = [{"_id":"1","subdata":[{"subid":"11","name":"A"},{"subid":"12","name":"B"}]},{"_id":"2","subdata":[{"subid":"12","name":"B"},{"subid":"33","name":"E"}]}];

const result = _.uniqBy(_.flatMap(myArray, 'subdata'), 'subid');

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>

使用 lodash/fp,您可以使用 _.flow() 使用相同的方法生成函数:

const fn = _.flow(
_.flatMap('subdata'),
_.uniqBy('subid')
);

const myArray = [{"_id":"1","subdata":[{"subid":"11","name":"A"},{"subid":"12","name":"B"}]},{"_id":"2","subdata":[{"subid":"12","name":"B"},{"subid":"33","name":"E"}]}];

const result = fn(myArray);

console.log(result);
<script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)'></script>

关于javascript - 如何从 JSON 对象数组中对 JSON 对象进行分组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58984081/

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