Search code examples
javascriptarraysunique

Javascript get unique value of an indented json


I have JSON array of objects with the following structure:

obj: [
    {   
        itemTitle: 'title-a',
        itemTags: [
            { tag: 'tag-a' },
            { tag: 'tag-b' }
        ]                       
    },
    {   
        itemTitle: 'title-b',
        itemTags: [
            { tag: 'tag-c' }
        ]                       
    },
    {   
        itemTitle: 'title-c',
        itemTags: [
            { tag: 'tag-c' },
            { tag: 'tag-b' }
        ]                       
    }
]

I need to extract distinct tags value in an array like this [tag-a, tag-b, tag-c] I'll try this approach:

const tagsArray = obj.map(elem => elem.itemTags);

var tags = [];
for (var i = 0; i < tagsArray.length; i++) {
    tags.push(tagsArray[i].map(item => item.tag))
}
//tagsArray[0]: [{"tag":"tag-a"},{"tag":"tag-b"}]
//tagsArray[1]: [{"tag":"tag-c"}]
//tagsArray[2]: [{"tag":"tag-c"},{"tag":"tag-b"}]

//tags: tag-a,tag-b,tag-c,tag-c,tag-b

const unique = [...new Set(tags)];
//unique: tag-a,tag-b,tag-c,tag-c,tag-b

it does not return distinct values


Solution

  • You can try getting the tag in the same loop with flatMap() and map()

    var obj = [
        {   
            itemTitle: 'title-a',
            itemTags: [
                { tag: 'tag-a' },
                { tag: 'tag-b' }
            ]                       
        },
        {   
            itemTitle: 'title-b',
            itemTags: [
                { tag: 'tag-c' }
            ]                       
        },
        {   
            itemTitle: 'title-c',
            itemTags: [
                { tag: 'tag-c' },
                { tag: 'tag-b' }
            ]                       
        }
    ]
    const tagsArray = obj.flatMap(elem => elem.itemTags.map(i=>i.tag));
    
    const unique = [...new Set(tagsArray)];
    console.log(unique)