数组数组转换为对象数组

时间:2017-09-05 02:29:47

标签: javascript arrays json loops object

所以我有一个JSON数组数组

[ [ "2015", "Honda", "CR-V", "1.5", "Turbo 7-Seater", "Automatic" ], [ "2016", "Mazda", "CX-5", "2.0", "Premium", "Manual" ] ] 

基本上,我需要使用JSON数组中的值以及下面的键创建一个新的JSON对象:

{
  "root": {
    "cars": [
      {
        "Year": "2015",
        "Make": "Honda",
        "Model": "CR-V",
        "Engine": "1.5",
        "Submodel": "Turbo 7-Seater",
        "Transmission": "Automatic"
      },
      {
        "Year": "2016",
        "Make": "Mazda",
        "Model": "CX-5",
        "Engine": "2.0",
        "Submodel": "Premium",
        "Transmission": "Manual"
      }
    ]
  }
}

我是JSON和Javascript的新手。有人可以提供一些提示和指导吗?谢谢!

2 个答案:

答案 0 :(得分:1)

首先是Javascript objectsJsonArray,而不是JSONObjectobject

如果map属性始终相同,您只需将var results = { "root": { "cars": arr.map(function(item) { return { "year": item[0], "make": item[1], "model": item[2], "engine": item[3], "submodel": item[4], "transmission": item[5] } }) } } 数组元素放入相应的对象中:

var arr = [
  ["2015", "Honda", "CR-V", "1.5", "Turbo 7-Seater", "Automatic"],
  ["2016", "Mazda", "CX-5", "2.0", "Premium", "Manual"]
];

var results = {
  "root": {
    "cars": arr.map(function(item) {
      return {
        "year": item[0],
        "make": item[1],
        "model": item[2],
        "engine": item[3],
        "submodel": item[4],
        "transmission": item[5]
      }
    })
  }
}

console.log(results);

<强>演示:

http://LocalHost:8080/shop/ss.php

答案 1 :(得分:1)

您可以将原始数组传递给此函数以获得预期效果。据我所知,你说你是JS的新手所以我的解决方案来自最简单的函数(JS的forEach);

var rootObj = [ [ "2015", "Honda", "CR-V", "1.5", "Turbo 7-Seater", "Automatic" ], [ "2016", "Mazda", "CX-5", "2.0", "Premium", "Manual" ] ];


function convert(arr) {
  var result = { root: { cars: [ ] } };
  arr.forEach(function(val) {
    result.root.cars.push({
      "Year": val[0],
      "Maker": val[1],
      "Model": val[2],
      "Engine": val[3],
      "Submodel": val[4],
      "Transmission": val[5]
    })
  });
  return result;
}

// You can test the result with this line of code
var output = convert(rootObj);
console.log('RESULT: ', JSON.stringify(output));