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

时间:2016-06-07 08:01:30

标签: javascript arrays

所以我被困在这几个小时,我无法找到解决这个问题的优雅解决方案。让我们说我有一个这样的数组:

[
   {
     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的单个字符串,用作每个&#34;主题&#34;&#34;的内容&#34;键?

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

5 个答案:

答案 0 :(得分:3)

您可以使用临时对象对其进行分组,并使用Array#forEach进行迭代。

  

forEach() 方法为每个数组元素执行一次提供的函数。

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);

答案 1 :(得分:1)

当使用ES6 Map对象时,可以简单地完成如下操作。我还从names数组的项目中删除了多余的content属性。

&#13;
&#13;
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"}],
 mapData = data.reduce((p,c) => p.has(c.topic) ? p.set(c.topic,p.get(c.topic).concat({question:c.question,
                                                                                        answer:c.answer}))
                                               : p.set(c.topic,[{question:c.question,
                                                                   answer:c.answer}]),new Map()),
  result = [...mapData].map(e => ({topic:e[0],content:e[1]}));
console.log(result);
&#13;
&#13;
&#13;

答案 2 :(得分:0)

试试这个:

var input = [
   {
     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"
   }
];
var tmp = input.reduce(function(topics, obj) {
  topics[obj.topic] = topics[obj.topic] || {topic: obj.topic, content: []};
  topics[obj.topic].content.push(obj);
  return topics;
}, {});
var output = Object.keys(tmp).map(function(key) {
  return tmp[key];
});
console.log(output);

答案 3 :(得分:0)

更实用的方法是使用Array.reduce。这也消除了对临时变量的需求:

System.IO.Compression.ZipFileExtensions

请参阅JS Bin的工作示例:
https://jsbin.com/yesucaquwa/1/edit?js,console

答案 4 :(得分:0)

有一个简单的功能。

var arr=[
   {
     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"
   }
]
function turnToOtherArray(arr){
    var result=[];
    for(var i=0,mamorize={};i<arr.length;i++){
        if(mamorize[arr[i].topic]){
            mamorize[arr[i].topic].push(arr[i].question)
        }else{
            mamorize[arr[i].topic]=[arr[i].question]
        }
    }
    for(var key in mamorize){
        result[result.length] = { "topic" : key , "content" : mamorize[key]}
    }
    return result;
}
console.log(turnToOtherArray(arr));