如何使用reduce将对象转换为对象数组?

时间:2019-03-27 06:40:53

标签: javascript

我想将对象转换为适合我需要的对象数组。我更喜欢使用最简单的解决方案和更少量的代码来编写。 json存储在“监视”变量中。

monitorings = [
{
    "id": 1,
    "survey_id": 1,
    "region_id": 9101,
    "month_id": 1,
    "target": 22,
    "progress": 22,
    "survey": {
      "name": "HPG",
      "category": "SHP"
    },
  },
  {
    "id": 2,
    "survey_id": 1,
    "region_id": 9102,
    "month_id": 1,
    "target": 10,
    "progress": 10,
    "survey": {
      "name": "SHPED",
      "category": "SHPED"
    },
  },
}
]

我的大脑只能在此代码之前思考

Object.entries(
  monitorings.reduce((monitorings, monitoring) => {
    const { name } = monitoring.survey

    monitorings[name] = monitorings[name]
                      ? [...monitorings[name], monitoring]
                      : [monitoring]

    return monitorings
  }, {})
)

实际输出

[
  "survey.name", [{grouped object}],
  "survey.name", [{grouped object}],
]  

预期产量

[
  "survey.category", [
    "survey.name", [{grouped object}],
      "survey.name", [{grouped object}],
  ]
 ,
 "survey.category", [
   "survey.name", [{grouped object}],
   "survey.name", [{grouped object}],
 ],
]

感谢您的帮助

-编辑-

分组对象的格式与原始对象的格式相同,如下所示

[
  {
    "id": 2,
    "survey_id": 1,
    "region_id": 9102,
    "month_id": 1,
    "target": 10,
    "progress": 10,
    "survey": {
      "name": "SHPED",
      "category": "SHPED"
    },
  },

  {same format as above},
  {same format as above},
  ...
],

1 个答案:

答案 0 :(得分:0)

我找到了答案Jar Files并对其进行了修改。

Object.entries(monitorings.reduce((map, obj) => {
  !map[obj.survey["category"]] 
    ? map[obj.survey["category"]] = {}  
    : [].concat(obj.survey["name"]).forEach(subEl => {
      !map[obj.survey["category"]][subEl]
        ? map[obj.survey["category"]][subEl] = []
        : map[obj.survey["category"]][subEl].push(obj);
  })

  return map;
  }, {})
)

解释

//return convert object into array of object
Object.entries(

//return new form of object
monitorings.reduce((map, obj) => {

  //if empty
  !map[obj.survey["category"]] 

    //create new empty object of survey["category"]
    ? map[obj.survey["category"]] = {}

    //else combine all of returned object of survey["name"] into empty array of object  
    : [].concat(obj.survey["name"])

        //iterate over obj.survey["name"]
        .forEach(subEl => {

          //if that object is empty
          !map[obj.survey["category"]][subEl]

            //create empty array of survey["category"][subEl]
            ? map[obj.survey["category"]][subEl] = []

          //else push every element of filtered original JSON into array of survey["category"][subEl]
          : map[obj.survey["category"]][subEl].push(obj);
  })

  //return grouped object
  return map;
  }, {})
)