gpt4 book ai didi

Javascript - 如何将数组列表转换为另一个键值数组列表?

转载 作者:行者123 更新时间:2023-11-30 09:48:34 25 4
gpt4 key购买 nike

所以我已经被这个问题难住了几个小时,我真的想不出一个优雅的解决方案来解决这个问题。假设我有一个这样的数组:

[
{
question: "what is your name?",
answer: "Ben",
topic: "names"
},
{
question: "what is your name?",
answer: "Ben",
topic: "names"
},
{
question: "What is dog's name?",
answer: "Snugglets",
topic: "names"
},
{
question: "What is your brother's age?",
answer: 55,
topic: "ages"
}
]

我怎样才能把它变成这样的数组?

[
{
topic: "names",
content: [...array of objects based on "names"...]
},
{
topic: "ages",
content: [...array of objects based on "ages"...]
}
]

我觉得这应该是一件非常容易的事情,但出于某种原因,我的大脑似乎无法理解解决方案。我在这里缺少什么?

更新:感谢所有回复!我没想到会有这么多方法来完成这个。我接受了其中一个答案,因为它与 ES6 相关,而且如果可能的话,我应该明确说明我希望学习 ES6 的实现方式:)

不过,我还必须说,需求也发生了一些变化,而不是预期的数组,就像这样:

[
{
topic: "names",
content: [...array of objects based on "names"...]
},
{
topic: "ages",
content: [...array of objects based on "ages"...]
}
]

数组需要看起来更像这样:

[
{
topic: "names",
content: '<div>
<h3>Question: What is your name?</h3>
<p>Answer: Ben</p>
</div>
<div>
<h3>Question: What is your dog's name?</h3>
<p>Answer: Snugglets</p>
</div>'
},
{
topic: "ages",
content: content: '<div>
<h3>Question: What is your age?</h3>
<p>Answer: 50</p>
</div>
<div>
<h3>Question: What is your brother's age?</h3>
<p>Answer: 52</p>
</div>'
}
]

通常我不喜欢只索取给我的代码,但是当涉及到通过算法转换数据时,我的 Javascript foo 似乎有点弱:( 关于如何将所有这些数组元素合并到一个包含 HTML 的单个字符串,用作每个“主题”的“内容”键?

此外,在 Stackoverflow 上的另一个问题中会更好吗?

最佳答案

您可以将它与一个临时对象分组并使用 Array#forEach 进行迭代.

The forEach() method executes a provided function once per array element.

var data = [{ question: "what is your name?", answer: "Ben", topic: "names" }, { question: "what is your name?", answer: "Ben", topic: "names" }, { question: "What is dog's name?", answer: "Snugglets", topic: "names" }, { question: "What is your brother's age?", answer: 55, topic: "ages" }],
group = [];

data.forEach(function (a) {
if (!this[a.topic]) {
this[a.topic] = { topic: a.topic, content: [] };
group.push(this[a.topic]);
}
this[a.topic].content.push(a);
}, Object.create(null));

console.log(group);

关于Javascript - 如何将数组列表转换为另一个键值数组列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37673725/

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