如何使用.map从一组对象创建一个数组数组?

时间:2016-11-17 20:22:41

标签: javascript

给出以下代码:

var data = [];
for (let i = 0; i <2; i++) {
  data.push({
    "a": "1",
    "b": "2"
  });
}

console.log(data);

data.map((el) => {
  var row = Object.keys(el).map(key => el[key]);
  console.log(row);
  return row;
});

console.log(data);

为什么这不会产生数组数组,例如:

[
  ["1", "2"],
  ["1", "2"]
]

以下是CodePen:http://codepen.io/24ma13wg/pen/MbbQZr

2 个答案:

答案 0 :(得分:-1)

差不多。您需要存储Array#map的结果。

var data = [], result;
for (let i = 0; i <2; i++) {
  data.push({
    "a": "1",
    "b": "2"
  });
}

result = data.map(el => Object.keys(el).map(key => el[key]));
// ^^^^^ missing assignment

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:-1)

如果要更新阵列,则应手动执行:

&#13;
&#13;
var data = [];
for (let i = 0; i <2; i++) {
  data.push({
    "a": 2*i,
    "b": 2*i+1
  });
}
console.log(data);
data.forEach((el,i,arr) => {
  arr[i] = Object.keys(el).map(key => el[key]);
});
console.log(data);
&#13;
&#13;
&#13;

另请考虑使用ES2017&#39; Object.values

data = data.map(Object.values);