[英]JavaScript How to loop through unique values of nested object
I am trying to loop through all unique values from a nested object. It seems like something like this should be easy, but I can't figure out how to do it.我正在尝试循环遍历嵌套 object 中的所有唯一值。看起来像这样的事情应该很容易,但我不知道该怎么做。
I have tried this我试过这个
const result = [...new Set(events.flatMap(({tags}) => tags))].sort()
And then when I echo out { result }
I ultimately get the output of unique values.然后当我回显
{ result }
时,我最终得到了 output 的唯一值。 But I want to use these values in the application.但我想在应用程序中使用这些值。 Somehow wrap each value in a
<button>
or something.以某种方式将每个值包装在
<button>
或其他东西中。
Below is my test object. Each item has an array of tags, and I want to be able to dynamically list out all unique tags.下面是我的测试 object。每个项目都有一个标签数组,我希望能够动态列出所有唯一标签。
I'd be very grateful for any help here.我将非常感谢这里的任何帮助。
Thanks in advance.提前致谢。
const events = [
{
id: 1,
name: "Event 1",
tags: ["tag 1", "tag 2", "tag 3"]
},
{
id: 2,
name: "Event 2",
tags: ["tag 1", "tag 3"]
},
{
id: 3,
name: "Event 3",
tags: ["tag 1", "tag 3", "tag 2"]
},
{
id: 4,
name: "Event 4",
tags: ["tag 1", "tag 5", "tag 3"]
},
{
id: 5,
name: "Event 5",
tags: ["tag 3"]
},
{
id: 6,
name: "Event 6",
tags: ["tag 2", "tag 3"]
}
]
export default function App() {
const events = [
{
id: 1,
name: "Event 1",
tags: ["tag 1", "tag 2", "tag 3"]
},
{
id: 2,
name: "Event 2",
tags: ["tag 1", "tag 3"]
},
{
id: 3,
name: "Event 3",
tags: ["tag 1", "tag 3", "tag 2"]
},
{
id: 4,
name: "Event 4",
tags: ["tag 1", "tag 5", "tag 3"]
},
{
id: 5,
name: "Event 5",
tags: ["tag 3"]
},
{
id: 6,
name: "Event 6",
tags: ["tag 2", "tag 3"]
}
];
const result = [...new Set(events.flatMap(({tags}) => tags))].sort();
return (
<div>
{
result.map((tag,i) => <h1 key={i}>{tag}</h1>)
}
</div>
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.