简体   繁体   中英

JavaScript - Distinct values in array from array of objects

I have a data like this:

data: [
    {id: 1, name: 'device1', status: ['online','idle']},
    {id: 2, name: 'device2', status: ['network-error']},
    {id: 3, name: 'device3', status: ['online','idle']},
    {id: 4, name: 'device4', status: ['offline','inoperative']},
    
    ...
]

I'm trying to get distinct values of status in an array like this:

['online', 'idle', 'network-error', 'offline', 'inoperative']

I used this code:

let status = [...new Set(data.map(({deviceTags}) => deviceTags))];

But it returns:

[["online", "idle"], ["network-error"], ["online", "idle"], ["offline", "inoperative"]]

How can achieve distinct values of them?

Use .flatMap() instead of .map()

The flatMap() method returns a new array formed by applying a given callback function to each element of the array, and then flattening the result by one level. It is identical to a map() followed by a flat() of depth 1, but slightly more efficient than calling those two methods separately.

 const data = [ {id: 1, name: 'device1', deviceTags: ['online','idle']}, {id: 2, name: 'device2', deviceTags: ['network-error']}, {id: 3, name: 'device3', deviceTags: ['online','idle']}, {id: 4, name: 'device4', deviceTags: ['offline','inoperative']} ] const status = [...new Set(data.flatMap(({deviceTags}) => deviceTags))]; console.log(status);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM