组合嵌套对象

时间:2016-12-23 16:08:04

标签: javascript jquery arrays json object

我有一个这样的对象:

"data" :[{"question": "FirtName", "answer": "Daniel"},
         {"question": "LastNane", "answer": "Daniel2"},
         {"question": "Age", "answer": "80"}]
  • 我想使用java脚本将其更改为此格式 "数据":

    ["FirtName" : "Daniel", "LastNane" : "Daniel2", "Age" : "80"]
    

请帮助我!

4 个答案:

答案 0 :(得分:1)

注意你的物体,这就是它应该看的东西。

var object={
  "data" :[
    {
      "question": "FirtName",
      "answer": "Daniel"
    },{
      "question": "LastNane",
      "answer": "Daniel2"
    },{
      "question": "Age",
      "answer": "80"
    }
  ]
};
var newObject={};

object.data.forEach(function(question){
  newObject[question.question]=question.answer;
  });
// {"FirtName" : "Daniel", "LastNane" : "Daniel2", "Age" : "80"}
console.log(newObject);

答案 1 :(得分:1)

您可以使用Array.prototype.reduce转换为您想要的对象 - 请参阅下面的演示:

var array = [{"question": "FirtName","answer": "Daniel"},{"question": "LastNane","answer": "Daniel2"}, {"question": "Age","answer": "80"}];

var result = array.reduce(function(p, c) {
  p[c.question] = c.answer;
  return p;
}, {});

console.log(result);

答案 2 :(得分:1)

此代码将为您提供所需的输出

var object = {
  "data": [{
    "question": "FirtName",
    "answer": "Daniel"
  }, {
    "question": "LastNane",
    "answer": "Daniel2"
  }, {
    "question": "Age",
    "answer": "80"
  }]
};

var result = '"data":' + JSON.stringify(object.data.reduce(function (result, item) {
  return result[item.question] = item.answer, result;
}, {})).replace('{', '[').replace('}', ']');
console.log(result);
// "data":["FirtName":"Daniel","LastNane":"Daniel2","Age":"80"]

答案 3 :(得分:1)

我提出了一个输入解决方案,作为对象数组,输出作为对象

.toString()