0

I'm trying to achieve from this array of objects one smaller array of objects with unique key/value pairs. This is the array from which I want to get a group and its value. This is the main 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
            }
           ]
        }
    }

And this is something I would like to achieve:

let result = [
{group: 'picturesWithDescription'},
{group: 'footers'},
{group: 'movies'}
]

1 Answer 1

2

Assuming that samples is an array as said in question.

Try following

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

OR

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

Sign up to request clarification or add additional context in comments.

1 Comment

Good to hear this :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.