如何解决根据嵌套对象数组中的键组合对象数组的结果
我有一组对象,我想根据特定的 id 过滤和组合结果。这是示例:
[
{
id: 1,items: [
{
id: 10,values: [11],},{
id: 20,values: [13,14,15],],{
id: 2,values: [12],];
这是预期的结果:
[
{
id: 10,values: [11,12],{
id: 20,];
我还需要过滤重复项。谢谢
注意:如果我想要这个结果怎么办?
[
{
// here I want value for id 10 (it will be always one number)
value: 11,// here I want values for id 20 (array of numbers) => remove possible duplicates
values: [13,{
// here I want value for id 10 (it will be always one number)
value: 12,];
我用 Map 尝试了相同的方法,但没有成功。基本上我想根据 id 组合值。
解决方法
- 您可以使用 Array.flatMap 过滤单个数组中的所有
items
。 - 然后使用
Array.reduce
重新创建数组并将基于id
的值推送到新的值对象中 - 并使用
Array.filter
忽略数组中的重复值 -
Object.values
只返回数组格式的对象值
年长
const arr = [ { id: 1,items: [ { id: 10,values: [11],},{ id: 20,values: [13,14,15],],{ id: 2,values: [12],];
const res = Object.values(arr.flatMap(({items})=> items)
.reduce((acc,{id,values})=>{
acc[id] = acc[id] ?? {id,values:[]};
//check the object exist or not
let newArr = acc[id]['values'].concat(values);
let valArr = newArr.filter((v,i)=>newArr.indexOf(v) === i)
//remove the duplicates
acc[id]['values'] = valArr
return acc
},{}))
console.log(res)
更新
const arr = [ { id: 1,];
function filterMethod(arr,value,values){
return arr.map(({items})=> ({
value:detector(items,value)[0],values:detector(items,values)
}))
}
function detector(items,idVal){
let ind = items.findIndex(({id})=> id === idVal);
return ind > -1 ? items[ind]['values'] : ['']
}
console.log(filterMethod(arr,10,20))
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。