Node.js将数组转换为对象数组

时间:2019-11-05 16:21:44

标签: node.js angular angular-material

我在Node.js中有一个rest API,该API输出如下数组:

[["Benni", 24, "Whatever"], ["Paul", 23, "Whatever"]]

现在为了将其用于Angular Material表中,我必须将数组设置为以下格式:

[{name: 'Benni', age: 24, Text: 'Whatever'}, {name: 'Paul', age: 23, Text: 'Whatever'},] 

我该如何实现?

3 个答案:

答案 0 :(得分:3)

您可以使用数组的Array.prototype.map方法。

只需在数组上调用一个映射,从数组项中依次获取数据,然后在map函数中返回所需的对象即可。

const arr = [
  ["Benni", 24, "Whatever"],
  ["Paul", 23, "Whatever"]
];

const remapped = arr.map((data) => {
  const [name, age, Text] = data;
  return {
    name,
    age,
    Text,
  };
});

console.log(remapped);

答案 1 :(得分:1)

非常容易:

let result = inputArr.map( innerArr => {name: innerArr[0], age: innerArr[1], Text: innerArr[2]});

答案 2 :(得分:0)

您可以按照以下步骤进行操作,

var data = [[ "Benni" , 24 , "Whatever" ],[ "Paul" , 23 , "Whatever" ]];

var collection = data.slice(); // make a copy
var keys = ["name","age","text"];

collection = collection.map(function (e) {
    var obj = {};

    keys.forEach(function (key, i) {
        obj[key] = e[i];
    });

    return obj;
});

收集对象将包含以下结果

    [
  {
    "name": "Benni",
    "age": 24,
    "text": "Whatever"
  },
  {
    "name": "Paul",
    "age": 23,
    "text": "Whatever"
  }
]

有关完整代码,请参见:JSFiddle