对象数组中的属性值的递归数组 [英] Recursive array of property values in array of objects

查看:83
本文介绍了对象数组中的属性值的递归数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要的是一组属性值,这些属性值是从一组对象中递归收集的,这就是我的意思:

What I need is an array of property values, recursively collected from an array of objects, this is what I mean:

const regions = [{
  name: 'Europe',
  subRegions: [{
    name: 'BeNeLux',
    territories: [{
      code: 'NL',
      name: 'Netherlands'
    }, {
      code: 'DE',
      name: 'Germany'
    }, {
      code: 'LU',
      name: 'Luxembourgh'
    }]
  }],
  territories: [{
    code: 'UK',
    name: 'United Kingdom'
  }, {
    code: 'AL',
    name: 'Albania'
  }, {
    code: 'ZW',
    name: 'Switzerland'
  }]
}]

我想在 regions 数组中获得所有国家/地区代码的数组.

I want to get an array of all the country codes in the regions array.

像这样:

const expectedOutput = ['NL', 'DE', 'LU', 'AL', 'ZW', 'UK'];

这是我尝试过的方法,部分起作用,但是不能正确收集它(我也非常想探索其他/功能性设置来解决此问题)

This what I have tried, which partly works but it's not collecting it correctly (I'm also very curious for exploring different / functional setups to solve this problem)

const getAllTerritoryCodesFromRegions = regions => {
  return regions
    .reduce(function r (output, region) {
      if (region?.subRegions?.length) {
        output.subRegions = region.subRegions.reduce(r, output)
      }

      if (region?.territories?.length) {
        output = [
          ...output,
          ...region.territories.map(t => t.code)
        ]
      }

      return output
    }, [])
}

推荐答案

假定 code 属性应始终包含国家/地区代码:

Assuming that the code properties should always contain the country codes:

在第一个调用中创建一个 one 数组可能比为每个调用创建一个数组并稍后尝试将其组合起来要容易.然后,您只需要在区域和地区上进行 forEach 并将代码推送到该数组:

It would probably be easier to create one array on the first call, which gets recursively passed down as a parameter, than to create an array for every call and try to combine it later. Then you just need to forEach over the regions and territories and push the code to that array:

const regions = [{
  name: 'Europe',
  subRegions: [{
    name: 'BeNeLux',
    territories: [{
      code: 'NL',
      name: 'Netherlands'
    }, {
      code: 'DE',
      name: 'Germany'
    }, {
      code: 'LU',
      name: 'Luxembourgh'
    }]
  }],
  territories: [{
    name: 'United Kingdom',
    code: 'UK'
  }, {
    code: 'AL',
    name: 'Albania'
  }, {
    code: 'ZW',
    name: 'Switzerland'
  }]
}];

const getAllTerritoryCodesFromRegions = (regions, allCodes=[]) => {
  regions.forEach(({ territories, subRegions }) => {
    if (territories) {
      territories.forEach(({ code }) => {
        allCodes.push(code);
      });
    }
    if (subRegions) {
      getAllTerritoryCodesFromRegions(subRegions, allCodes);
    }
  });
  return allCodes;
};
console.log(
  getAllTerritoryCodesFromRegions(regions)
);

这篇关于对象数组中的属性值的递归数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆