如何使用另一个对象数组中的唯一键/值对创建对象数组?

时间:2018-05-30 09:31:35

标签: javascript arrays

我正试图从这个对象数组中实现一个具有唯一键/值对的较小对象数组。 这是我想从中获取组及其值的数组。 这是主要的对象数组:

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'}
]

1 个答案:

答案 0 :(得分:0)

假设样本数组,如上所述。

尝试以下



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);