创建数组的子数组

时间:2017-08-25 14:04:59

标签: javascript arrays typescript

创建数组子数组的最佳和最有效的方法是什么?我有一个对象数组如下:

bigArray = [
    {
        id: 1,
        name: "Marc",
        age: 29
    },
    {
        id: 2,
        name: "Caroline",
        age: 27
    },
    {
        id: 3,
        name: "John",
        age: 30
    }];

我想生成3个子数组,例如

  • ids = [1,2,3]
  • names = [" Marc"," Caroline"," John"]
  • 年龄= [29,27,30]

我尝试使用嵌套" for"循环并用map()方法对其进行实验,但我不相信这是最干净的方法。特别是因为我可能有每个对象的几十个参数(即"姓氏,城市,汽车...)

1 个答案:

答案 0 :(得分:2)

假设所有对象在数组中都有相同的键,我会这样做:

bigArray = [
    {
        id: 1,
        name: "Marc",
        age: 29
    },
    {
        id: 2,
        name: "Caroline",
        age: 27
    },
    {
        id: 3,
        name: "John",
        age: 30
    }];

let output = {}

Object.keys(bigArray[0]).forEach( key => {
	output[key+"s"] = bigArray.map( obj => obj[key] )	
})

// Or as a one-liner, to show off to your friends
Object.keys(bigArray[0]).forEach( key => output[key+"s"] = bigArray.map( obj => obj[key] ))

console.log(output)

然后,您使用output.namesoutput.ages

访问数据