gpt4 book ai didi

Javascript获取缩进json的唯一值

转载 作者:行者123 更新时间:2023-12-04 07:48:32 25 4
gpt4 key购买 nike

我有 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
它不会返回不同的值

最佳答案

您可以尝试使用 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)

关于Javascript获取缩进json的唯一值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67089046/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com