javascript - 使用每个数组的对象键将嵌套数组递归转换为嵌套对象

标签 javascript arrays database object data-structures

我想更改此数据结构:

[ { sectionName: 'SectionOne',
    ingredients: [ {ingredient: 'sugar'}, {ingredient: 'flour'} ]},
  { sectionName: 'SectionTwo',
    ingredients: [ {ingredient: 'eggs'}, {ingredient: 'water'} ] },
 ]

对此:

{ SectionOne:
       { sectionName: 'SectionOne',
         ingredients: {
           sugar: { ingredient: 'sugar' },
           flour: { ingredient: 'flour' }
          }
        },
{ SectionTwo:
       { sectionName: 'SectionTwo',
         ingredients: {
           eggs: { ingredient: 'eggs' },
           water: { ingredient: 'water' }
          }
        },

 }

换句话说,我想对每个要转换为对象的数组使用对象的键。

您可以在此找到数据结构的示例 jsfddle 连同我的尝试。

到目前为止,使用 lodash 或 vanillaJS 我只能转换外部数组。 我无法设法递归地使用 _.mapKeys()、for 循环或类似的方法来获得所需的结构。我确信我错过了一个愚蠢的观点,但我无法解决这个问题。

非常感谢您的帮助!

最佳答案

您可以映射一个数组并非常简单地构造您的对象:

const data = [ 
  { sectionName: 'SectionOne',
    ingredients: [ {ingredient: 'sugar'}, {ingredient: 'flour'} ]},
  { sectionName: 'SectionTwo',
    ingredients: [ {ingredient: 'eggs'}, {ingredient: 'water'} ] },
 ];
 
const res = Object.assign(...data.map(el => ({ // for every element
  [el.sectionName]: {
    sectionName: el.sectionName,
    ingredients: Object.assign(...el.ingredients.map(e => ({[e.ingredient]: e}))) // assign each object inside array
    }
  })))

console.log(res)
console.log(res.SectionOne.ingredients.sugar)

这里[something]表示法创建一个键,其名称是something变量的值。三个点 ... 将数组分散为单独的元素,就像这些元素只是用逗号分隔一样。

关于javascript - 使用每个数组的对象键将嵌套数组递归转换为嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44593583/

相关文章:

javascript - 在特定索引上启动 for 循环并循环数组长度

java - 如何在 Hibernate 中的同一个表上建模 ManyToOne 和 ManyToMany 关系?

javascript - 一次只显示三个 Div

javascript - 多边形裁剪

javascript - 为什么我不能将新元素插入新数组?

php - 获取数组的前 N ​​个元素?

javascript - 注入(inject)带有路由器链接的模板组件时的 Angular2 路由器链接问题

javascript - 如何转换日期时间以下格式?

mysql数据库结构

sql - CodeIgniter - 继续出现 SQL 错误?