展平嵌套的对象数组,将键重命名为迭代器

时间:2018-05-09 21:02:40

标签: javascript object ecmascript-6 lodash flatten

我有一个对象数组,每个对象看起来如下(一个轮询响应):

{
"slug": "18-AZ-Gov-GE-DvF",
"name": "2018 Arizona Gubernatorial GE",
"tags": [],
"charts": [],
"election_date": "2018-11-06",
"n_polls": 1,
"created_at": "2017-06-13T13:32:26.000Z",
"responses": [
 {
 "label": "Ducey",
 "name": "Doug Ducey",
 "party": "Republican",
 "incumbent": true
 },
 {
 "label": "Farley",
 "name": "Steve Farley",
 "party": "Democrat",
 "incumbent": false
 },
 {
 "label": "Other",
 "name": "Other",
 "party": null,
 "incumbent": false
 },
 {
 "label": "Undecided",
 "name": "Undecided",
 "party": null,
  "incumbent": false
 }
]
},

我需要展平responses键访问的数组,以便每个对象都键入其迭代器。

最终对象应如下所示:

{
"slug": "18-AZ-Gov-GE-DvF",
"name": "2018 Arizona Gubernatorial GE",
"tags": [],
"charts": [],
"election_date": "2018-11-06",
"n_polls": 1,
"created_at": "2017-06-13T13:32:26.000Z",
 "label1": "Ducey",
 "name1": "Doug Ducey",
 "party1": "Republican",
 "incumbent1": true
 "label2": "Farley",
 "name2": "Steve Farley",
 "party2": "Democrat",
 "incumbent2": false
 "label3": "Other",
 "name3": "Other",
 "party3": null,
 "incumbent3": false
 "label4": "Undecided",
 "name4": "Undecided",
 "party4": null,
  "incumbent4": false
},

在展平或对集合执行时,answers I've seen不会重命名对象键。

我尝试了几种解决方案,但是在我真正潜入之前想看看是否有一种简单的es6方式。

3 个答案:

答案 0 :(得分:2)

使用数组.reduce方法可能在此处运行良好。由于reduce回调将接收当前索引作为第三个参数,因此您可以使用它来创建您正在寻找的键。

示例:

const myArray = [
 {
 "label": "Ducey",
 "name": "Doug Ducey",
 "party": "Republican",
 "incumbent": true
 },
 {
 "label": "Farley",
 "name": "Steve Farley",
 "party": "Democrat",
 "incumbent": false
 },
 {
 "label": "Other",
 "name": "Other",
 "party": null,
 "incumbent": false
 },
 {
 "label": "Undecided",
 "name": "Undecided",
 "party": null,
  "incumbent": false
 }
]

const flattened = myArray.reduce((flat, item, index) => ({
    ...flat,
    ...Object.keys(item).reduce((numbered, key) => ({
        ...numbered,
        [key + (index+1)]: item[key],
    }), {}),
}), {});

console.log(flattened);

答案 1 :(得分:2)

您可以使用final ResponseModel item = hashMap.get("response"); 浏览forEach数组,并在对象上为每个对象中的responses分配一个新密钥。之后只有entries原始delete数组:

responses

答案 2 :(得分:1)

您可以对响应和其他数据进行解构,然后使用索引键减少对一个对象的每个响应,然后通过对象扩展运算符组合结果:

const { responses, ...other } = data
const indexedResponses = responses.reduce((acc, r, i) => {
  Object.entries(r).forEach(([key, value]) => {
    acc[`${key}${i + 1}`] = value
  })
  return acc
}, {})
const result = { ...other, ...indexedResponses }