【问题标题】:Pull items from nested object virtuals into the parent object array将嵌套对象虚拟对象中的项目拉入父对象数组
【发布时间】:2021-07-17 11:57:47
【问题描述】:

我想采用这个对象数组,其中一些对象包含相似架构的数组,并创建一个新数组,它们都在同一级别。

[
  {
   "name": "United States",
   "slug": "united-states",
   "states":[
     {
      "name": "Arizona",
      "slug": "arizona"
     },
     {
      "name": "California",
      "slug": "california"
     }
    ]
  },
  {
   "name": "Canada",
   "slug": "canada",
  }

]

这应该是最终结果:

[
  {
   "name": "United States",
   "slug": "united-states"
  },
  {
   "name": "Arizona",
   "slug": "arizona"
  },
  {
   "name": "California",
   "slug": "california"
  },
  {
   "name": "Canada",
   "slug": "canada",
  }

]

【问题讨论】:

  • 你为此做了什么?此外,您的输入可以深度嵌套给出一些关于它可能有多复杂的基本概念。

标签: javascript arrays json javascript-objects


【解决方案1】:

使用Array#flatMap

const data = [
  {
    "name": "United States",
    "slug": "united-states",
    "states":[
      { "name": "Arizona", "slug": "arizona" },
      { "name": "California", "slug": "california" }
    ]
  },
  { "name": "Canada", "slug": "canada" }
];

const res = data.flatMap(({ name, slug, states = [] }) => ([
  { name, slug },
  ...states
]));

console.log(res);

【讨论】:

  • 在 Nuxt、asyncData 生命周期中出现“flatMap is not a function”错误,试图找出为什么我无法在此处访问该函数
  • 你能分享更多关于用例和错误的细节
【解决方案2】:

您可以创建一个迭代器来遍历树,然后将其消耗到一个数组中。这适用于更深的嵌套级别,并且不需要知道哪个属性具有子记录。它假定具有 Array 值的属性持有子树:

function * traverse(forest) {
    for (const item of forest) {
        const arrayKey = Object.entries(item).find(([k, v]) => Array.isArray(v))?.[0];
        const { [arrayKey]: children, ...rest } = item;
        yield rest;
        if (children) yield * traverse(children);
    }
}

const data = [{"name": "United States","slug": "united-states","states":[{ "name": "Arizona", "slug": "arizona" },{ "name": "California", "slug": "california" }]},{ "name": "Canada", "slug": "canada" }];

const res = [...traverse(data)];

console.log(res);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-17
    • 2020-03-20
    • 1970-01-01
    • 2014-09-13
    • 2019-04-26
    • 2015-02-12
    • 2016-12-13
    相关资源
    最近更新 更多