将一个数组内的对象转换为多个数组

时间:2018-02-08 15:24:26

标签: javascript arrays object

我如何转换

const peopleArray = [
  { id: 123, name: "dave", age: 23 },
  { id: 456, name: "chris", age: 23 },
  { id: 789, name: "bob", age: 23 },
  { id: 101, name: "tom", age: 23 },
  { id: 102, name: "tim", age: 23 }
]

const peopleArray = [[{ id: 123, name: "dave", age: 23 }],
      [{ id: 456, name: "chris", age: 23 }],
      [{ id: 789, name: "bob", age: 23 }],
      [{ id: 101, name: "tom", age: 23 }],
      [{ id: 102, name: "tim", age: 23 }]]

我感谢任何帮助。我可以使用ES6方法吗?不想使用lodash或任何其他库。

1 个答案:

答案 0 :(得分:2)

您可以Array.prototype.map()并将每个值包装在数组文字中:

const peopleArray = [
  { id: 123, name: "dave", age: 23 },
  { id: 456, name: "chris", age: 23 },
  { id: 789, name: "bob", age: 23 },
  { id: 101, name: "tom", age: 23 },
  { id: 102, name: "tim", age: 23 }
];

console.log(peopleArray.map(person => [person]));