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

如何在JavaScript中获取对象数组中子对象的属性值

提取所有城市名称的解决方案

这里提供几种常用的JavaScript实现方式,都能得到你需要的城市名称数组:

方法一:使用flatMap(最简洁)

flatMap会先对数组每个元素执行映射,再自动将结果展平一层,非常适合这种嵌套数组的提取场景:

const cityNames = states.flatMap(state => state.cities.map(city => city.name));
console.log(cityNames); // 输出: ["foo", "joo", "goo", "tyu", "ery", "doo", "eee", "qqq", "www"]

方法二:使用reduce累加

通过reduce逐步收集每个州的城市名称,用concat合并数组:

const cityNames = states.reduce((result, state) => {
  return result.concat(state.cities.map(city => city.name));
}, []);
console.log(cityNames);

方法三:forEach循环手动收集

逻辑最直观,适合刚接触JS的开发者理解:

const cityNames = [];
states.forEach(state => {
  state.cities.forEach(city => {
    cityNames.push(city.name);
  });
});
console.log(cityNames);

注意:你的原始代码中字符串值(比如telangana、foo)没有加引号,实际运行时会报错,需要修正为字符串形式(如name: "telangana")。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 22:40:27