You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在JavaScript中从嵌套对象提取指定数组的实现方法问询

嘿,我来给你分享几个从这个嵌套JavaScript对象里提取指定数组的实用方案,根据你要提取的目标内容不同,咱们可以用不同的数组方法组合来实现:

1. 提取所有国家的产品合并成一个数组

如果想把所有国家的products数组合并成一个大数组,用flatMap是最简洁高效的方式——它会先遍历每个国家取出产品数组,再自动扁平化层级:

const input = { 
  "countryList": [ 
    { 
      "label": "Australia", 
      "id": "555", 
      "productHierarchy": "ABC", 
      "locked": "true", 
      "products": [ 
        { "id": "342", "label": "342- Test", "description": "Test" }, 
        { "id": "123456", "label": "123456- Test", "description": "Test" } 
      ] 
    }, 
    { 
      "label": "Brazil", 
      "id": "888", 
      "productHierarchy": "XYZ", 
      "locked": "true", 
      "products": [ 
        { "id": "987", "label": "987- Test", "description": "Test" } 
      ] 
    } 
  ] 
};

// 提取所有产品合并为单个数组
const allProducts = input.countryList.flatMap(country => country.products);
console.log(allProducts);

2. 提取特定国家的产品数组

如果只需要某一个国家的产品,比如澳大利亚的,先通过find定位到目标国家对象,再取出它的products(记得加个空数组兜底,避免找不到国家时报错):

// 提取Australia的产品数组
const targetCountry = input.countryList.find(country => country.label === "Australia");
const australiaProducts = targetCountry ? targetCountry.products : [];
console.log(australiaProducts);

3. 提取所有产品的特定字段组成数组

比如只想收集所有产品的id,可以用flatMap嵌套map来实现:

// 提取所有产品的id组成数组
const allProductIds = input.countryList.flatMap(country => 
  country.products.map(product => product.id)
);
console.log(allProductIds); // 输出: ["342", "123456", "987"]

要是想保留国家和产品id的关联,也可以用map返回带国家标识的对象:

// 按国家分组提取产品id列表
const countryProductIds = input.countryList.map(country => ({
  countryName: country.label,
  productIds: country.products.map(p => p.id)
}));
console.log(countryProductIds);

4. 过滤出符合条件的产品数组

如果需要筛选特定条件的产品(比如id大于500的),可以把flatMap和filter结合起来:

// 提取所有id数值大于500的产品
const filteredProducts = input.countryList.flatMap(country => 
  country.products.filter(product => parseInt(product.id) > 500)
);
console.log(filteredProducts); // 输出id为123456和987的产品对象

其实核心思路就是利用JavaScript数组的flatMap、map、find、filter这些方法来遍历和处理嵌套结构,根据你的具体需求组合就行~

内容的提问来源于stack exchange,提问作者Sheena

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 07:39:59