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

标签 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 方法。

最佳答案

使用数组.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);

关于javascript - 展平对象的嵌套数组,将键重命名为迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50262000/

相关文章:

javascript - 为什么jQuery动画只运行一次

oop - 怎么可能有一个纯面向对象的语言呢?

javascript - 从给定的长日期转换为适当的日期格式

javascript - 清洁代码 : try/catch in Promise

javascript - 在jquery文件上传插件的fileuploadsend事件中检索jqXHR?

javascript - 如何使用 Backbone.js 实现 "highlight mode"?

php - 奇怪的 AJAX 行为 - 一次没有保存正确的数据

javascript - 通过 Object.assign 中的父赋值来分配嵌套在对象中的许多值

python - 我可以使用该类的对象访问类变量吗

javascript - 我如何将一个大对象映射到 es6 中的数组