gpt4 book ai didi

javascript - 使用javascript map将嵌套数组扩展为行

转载 作者:搜寻专家 更新时间:2023-11-01 00:27:12 26 4
gpt4 key购买 nike

如何使用 Array.prototype.map() 来转换这个数据结构:

[
{text: "sometext", tags: ["t1", "t2", "t3"]},
{text: "sometext2", tags: ["t4", "t5", "t6"]}
]

进入这个数据结构?

[
{tag: "t1", text: "sometext"},
{tag: "t2", text: "sometext"},
{tag: "t3", text: "sometext"},
{tag: "t4", text: "sometext2"},
{tag: "t5", text: "sometext2"},
{tag: "t6", text: "sometext2"}
]

最佳答案

你可以参加(即将到来的)Array#flatMap并映射内部数组。

var data = [{ text: "sometext", tags: ["t1", "t2", "t3"] }, { text: "sometext2", tags: ["t4", "t5", "t6"] }],
result = data.flatMap(({ text, tags }) => tags.map(tag => ({ tag, text })));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

结果为 Array#reduce .

var data = [{ text: "sometext", tags: ["t1", "t2", "t3"] }, { text: "sometext2", tags: ["t4", "t5", "t6"] }],
result = data.reduce((r, { text, tags }) => [...r, ...tags.map(tag => ({ tag, text }))], []);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 使用javascript map将嵌套数组扩展为行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57383633/

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