以属性为键的对象到对象的数组

时间:2018-10-23 10:14:12

标签: javascript arrays object reduce

我需要一些帮助来从对象数组中获取对象,这些键的键来自初始数组中对象的嵌套属性。这是初始数组:

[  
   {  
      "id":{  
         "colName":"columnA",
         "recId":"123"
      },
      "desc":"this is a description for A",
      "resCode":"-1"
   },
   {  
      "id":{  
         "colName":"columnB",
         "recId":"123"
      },
      "desc":"this is a  description for B",
      "resCode":"-1"
   },
   {  
      "id":{  
         "colName":"columnC",
         "recId":"234"
      },
      "desc":"description for column c ",
      "resCode":"-1"
   }
];

我想要的输出是这样:

{
    123: {
        columnA: {
            desc: "this is a description for A",
            rescode: "-1"
        }
        columnB: {
            desc: "this is a description for B",
            rescode: "-1"
        }
    },
    234: {
        columnC: {
            desc: "description for column c ",
            resCode: "-1",
        }
    }
}

我尝试使用reduce来这样做,但是我遇到了问题。我不知道如何(以及何时)“清除”临时变量,因此我只能拥有属于一个recId的列名。

    const initialArray =  [
     {
      "id": {
        "colName": "columnA",
        "recId": "123"
      },
      "desc": "this is a description for A",
      "resCode": "-1"
    },
    {
      "id": {
        "colName": "columnB",
        "recId": "123"
      },
      "desc": "this is a  description for B",
      "resCode": "-1"
    },
    {
      "id": {
        "colName": "columnC",
        "recId": "234"
      },
      "desc": "description for column c ",
      "resCode": "-1"
    }
  ];
    let temp = {};
    const mappedObj = initialArray.reduce((obj, item) => {
      temp[item.id.colName] = Object.assign({}, {desc: item.desc}, {resCode: item.resCode} );
      obj[item.id['recId']] = Object.assign({},  temp);
      return obj;
    }, {});
    console.log(mappedObj);

1 个答案:

答案 0 :(得分:0)

您不需要在reduce外部维护临时变量,只需在reduce本身中处理相同的操作即可

const initialArray =  [
     {
      "id": {
        "colName": "columnA",
        "recId": "123"
      },
      "desc": "this is a description for A",
      "resCode": "-1"
    },
    {
      "id": {
        "colName": "columnB",
        "recId": "123"
      },
      "desc": "this is a  description for B",
      "resCode": "-1"
    },
    {
      "id": {
        "colName": "columnC",
        "recId": "234"
      },
      "desc": "description for column c ",
      "resCode": "-1"
    }
  ];
    const mappedObj = initialArray.reduce((obj, item) => {
      obj[item.id.recId] = {...(obj[item.id.recId] || {}), [item.id.colName]: {desc: item.desc, resCode: item.resCode}}
      return obj;
    }, {});
    console.log(mappedObj);