将数组数组转换为对象数组

时间:2019-02-20 04:49:24

标签: javascript

我有一个数组数组(二维数组),我想将其转换为对象数组。在结果数组中,我希望每个对象都有一个键名(请参见下面的预期输出)

data = [
 ['Apple', 'Orange', 'Banana', 'Pears', 'Peach'],
 [40, 35, 25, 58, 84],
 [2, 4, 4, 3, 1, 2],
 ['Red', 'Yellow', 'Green', 'Violet', 'Blue']
];

我的预期结果:

expected_result = [
  {name: 'Apple', price: 40, quantity: 2, color: 'Red'},
  {name: 'Orange', price: 35, quantity: 4, color: 'Yellow'},
  {name: 'Banana', price: 25, quantity: 4, color: 'Green'},
  {name: 'Pears', price: 58, quantity: 1, color: 'Violet'},
  {name: 'Peach', price: 84, quantity: 2, color: 'Blue'}
];

注意data中每个数组的迭代应该是连续的,以便给出预期的结果

3 个答案:

答案 0 :(得分:1)

似乎quantity值中还有一项。我已经更新 [2, 4, 4, 3, 1, 2][2, 4, 4, 1, 2]已删除3以匹配结果,希望它有错字。

let data = [
  ["Apple", "Orange", "Banana", "Pears", "Peach"],
  [40, 35, 25, 58, 84],
  [2, 4, 4, 1, 2],
  ["Red", "Yellow", "Green", "Violet", "Blue"]
];

let output = [];
let props = ["name", "price", "quantity", "color"];

function updateInfo(row, prop){
  row.filter((value, index) => {
    if (output[index]) {
      output[index][prop] = value;
    } else {
      output.push({
        [prop]: value
      });
    }
  });
};

data.filter((row, index) => {
  updateInfo(row, props[index]);
});



console.log(output);

答案 1 :(得分:1)

一个解决方案是首先在要分配给它们的 $(document).ready(function () { $("#categoriesId").change(function () { var cid = $("#categoriesId").val(); $.ajax({ url: 'fetchProductData.php', method: 'POST', data: {cid : cid }, success:function(data){ $("#product").html(data);//here response from server will be display in #product } }); }); 索引和outter-array(或property)名称之间创建一个Array.reduce()(但是可以这样)像这样的key数组来代替)。另外,您可以获取内部数组的["name","price","quantity","color"],以便稍后检查是否具有所有属性的minimun length是否未创建。完成此预初始化后,可以使用https://material.angular.io/components/dialog/api#MatDialogContent生成预期结果:

objects

答案 2 :(得分:1)

在我看来,最简单(不是最有效的)解决方案 是简单地循环遍历该数组,然后添加到另一个数组中。

let arr = [
  ['Apple', 'Orange', 'Banana', 'Pears', 'Peach'],
  [40, 35, 25, 58, 84],
  [2, 4, 4, 1, 2],
  ['Red', 'Yellow', 'Green', 'Violet', 'Blue']
];
let keys = ["name", "price", "quantity", "color"];
let output = [];

//Add's blank objects too the output array
for (let i = 0; i < arr[0].length; i++) {
  output.push({});
}

//Loops through the array
for (let i = 0; i < arr.length; i++) {
  //Loops through the sub array
  for (let x = 0; x < arr[i].length; x++) {
    //Adds the sub array to the key that corresponds to it
    output[x][keys[i]] = arr[i][x];
  }
}

console.log(output);