合并多个列表到单个数组

时间:2019-06-19 14:38:10

标签: javascript typescript

copySource(copySource),而我的脚本{ "data": [ {"firstName": "Achmad"}, {"lastName": "a"} ] }来自var body = request.body;for(var i = 0;i < body.data.length;i++){var obj = body.data[i];var keyes = Object.keys(obj);}的问题响应就是这样的列表var keyes = Object.keys(obj);,我想这样[ 'firstName' ] [ 'lastName' ]

谢谢。

3 个答案:

答案 0 :(得分:0)

已编辑:您可以concat数组中的每一项:

const body = {
  "data": [
    {"firstName": "Achmad"},
    {"lastName": "a"}
  ]
};

let result = [];
for (item of body.data) {
  result = result.concat(Object.keys(item));
}

console.log(result); // -> ['firstName', 'lastName']

答案 1 :(得分:0)

假设每个数组都是父数组的元素,则可以使用Array.prototype.reduce来实现此目的:

const flat = [
  ["aku"],
  ["dia"],
  ["ia"]
].reduce((accum, el) => accum.concat(el), [])

console.log(flat);

答案 2 :(得分:-2)

也许您想做这样的事情

var body = request.body;
var keyes = [];
for(var i = 0; i < body.data.length; i++){
    var obj = body.data[i];
    keyes.push( Object.keys(obj) );
}