【问题标题】:Getting access to deep nested arrays within objects访问对象内的深层嵌套数组
【发布时间】:2017-12-31 19:09:14
【问题描述】:

这是一个包含对象的数组的对象(类似于您可能从 API 返回的 JSON)

  const business = {
  name: 'Google',
  location: 'Venice, Ca',
  services: [
    {
      name: 'Google Voice',
      requests: [
        {
          summary: 'Read my lips',
          details: 'Details of of the request...',
        },
        {
          summary: 'Log in with face recoginition',
          details: 'Details of of the request...',
        },
      ],
    },
    {
      name: 'Google Maps',
      requests: [
        {
          summary: 'Make it rain',
          details: 'Details of of the request...',
        },
        {
          summary: 'Make it shine',
          details: 'Details of of the request...',
        },
      ],
    },
  ],
};

要访问公司名称 - 它是 business.name -> Google

要访问业务中的服务数组,我可以执行以下操作:

const services = business.services -> 现在我有了我的服务数组并且可以映射到它:

services.map(service => {
 return services.name
}

我会得到 -> ['Google Voice', 'Google Maps']

但是服务有它自己的嵌套数组(请求)。现在我可以通过以下方式访问它:

services.requests[0] 或 [1]

问题是:我如何将请求“提取”到它自己的变量中,以便我也可以映射它而不必使用 [0][1] 等...

【问题讨论】:

  • 可以在该嵌套数组上使用任何数组方法。你到底想用它们做什么?

标签: javascript multidimensional-array javascript-objects


【解决方案1】:

如果你想要一个数组,你可以只使用map,如果你想扁平化它使用reduce

 const reqs = business.services.map(service => service.requests);
  console.log(reqs);

  const flat = business.services.reduce((acc, service) => [...acc, ...service.requests], []);

  console.log(flat);

【讨论】:

    猜你喜欢
    • 2020-12-15
    • 2022-11-04
    • 2019-02-17
    • 1970-01-01
    • 1970-01-01
    • 2021-02-20
    • 2020-04-13
    • 2020-01-30
    • 1970-01-01
    相关资源
    最近更新 更多