[英]How do I assign property values for objects in one array based on key/value pairs in another?
[英]How to create array of objects with unique key/values pairs from another array of objects?
我正在尝试从此对象数组中实现一个具有唯一键/值对的较小对象数组。 这是我要从中获取组及其值的数组。 这是对象的主要数组:
let samples = {
{
id: 2,
group: 'picturesWithDescription',
elements: [
{
id: 1
},
{
id: 2
}
]
},
{
id: 3,
group: 'footers',
elements: [
{
id: 1
},
{
id: 2
}
]
},
{
id: 4,
group: 'movies',
elements: [
{
id: 1
},
{
id: 2
}
]
},
{
id: 4,
group: 'movies',
elements: [
{
id: 1
},
{
id: 2
}
]
}
}
这是我想要实现的目标:
let result = [
{group: 'picturesWithDescription'},
{group: 'footers'},
{group: 'movies'}
]
假设样本是一个有问题的数组 。
尝试跟随
let samples = [{id:2,group:'picturesWithDescription',elements:[{id:1},{id:2}]},{id:3,group:'footers',elements:[{id:1},{id:2}]},{id:4,group:'movies',elements:[{id:1},{id:2}]},{id:4,group:'movies',elements:[{id:1},{id:2}]}]; /* 1. Create an array with only group names ** 2. Convert it into Set to remove duplicates. ** 3. Convert back to array. ** 4. Create an array with object with group property. */ let result = [...new Set(samples.map(({group}) => group))].map((group) => {return {group}}); console.log(result);
要么
let samples = [{id:2,group:'picturesWithDescription',elements:[{id:1},{id:2}]},{id:3,group:'footers',elements:[{id:1},{id:2}]},{id:4,group:'movies',elements:[{id:1},{id:2}]},{id:4,group:'movies',elements:[{id:1},{id:2}]}]; /* 1. Reduce the array into an object with group names as key (removes duplicate) ** 2. Iterate over the keys (group names) and create an object with group property*/ let result = Object.keys(samples.reduce((a,{group}) => {a[group] = group; return a}, {})).map((group) => {return {group}}); console.log(result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.