Javascript 获取缩进的唯一值 json

Javascript get unique value of an indented json

我有 JSON array of objects 具有以下结构:

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

我需要像这样在数组中提取不同的标签值 [tag-a, tag-b, tag-c] 我会尝试这种方法:

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

它没有 return 个不同的值

问题

您正在将数组推入 tagsArray 中的每个项目。内容看起来像

[["tag-a","tag-b"],["tag-c"],["tag-c","tag-b"]]

趁你需要

["tag-a","tag-b","tag-c","tag-c","tag-b"]

解决方案

==> 使用 concat 代替 push

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

var tags = [];
const tagsArray = obj.map(elem => elem.itemTags);
for (var i = 0; i < tagsArray.length; i++)
    tags = tags.concat(tagsArray[i].map(item => item.tag)); // Use concat instead of push
const unique = [...new Set(tags)];
console.log(unique);

重构代码

您可以使用Array#flatMap

const 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(({itemTags}) => itemTags.map(({tag}) => tag));
console.log([...new Set(tagsArray )]);

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


您可以尝试在与 flatMap()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)

let t=arr.flatMap(item=>item.itemTags.flatMap(tag=>Object.values(tag)))
u = new Set([...t])