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

如何优雅实现可指定父字段的数组扁平化?

Elegant Way to Flatten Your Nested Array

Great question—ditching nested loops for more declarative array methods makes your code cleaner and easier to maintain. In JavaScript, the flatMap() method is perfect for this scenario since it combines mapping and flattening into a single step. Here's how to use it:

Basic Version (Keep Only Specified Parent Fields)

For your example where you only need the country field from the parent objects:

const originalData = [
  {"id":1,"country":"US","area":1,"values":[{"city":"Chicago"},{"city":"New York"}]},
  {"id":2,"country":"Canada","area":2,"values":[{"city":"Toronto"},{"city":"Quebec"}]}
];

const flattenedData = originalData.flatMap(parent => 
  parent.values.map(city => ({
    country: parent.country,
    city: city.city
  }))
);

console.log(flattenedData);

This will produce exactly your desired output:

[ {"country":"US","city":"Chicago"}, {"country":"US","city":"New York"}, {"country":"Canada","city":"Toronto"}, {"country":"Canada","city":"Quebec"} ]

Flexible Versions (Support Multiple/All Parent Fields)

If you want to keep more than just country, or even all parent fields except the nested values array, you can use the spread operator (...) to simplify things:

Keep All Parent Fields Excluding values

const flattenedData = originalData.flatMap(parent => {
  // Extract values and the rest of the parent fields
  const { values, ...parentProps } = parent;
  // Merge each city object with the parent props
  return values.map(city => ({ ...parentProps, ...city }));
});

Keep Specific Parent Fields (e.g., country and area)

const flattenedData = originalData.flatMap(parent => 
  parent.values.map(city => ({
    country: parent.country,
    area: parent.area,
    city: city.city
  }))
);

Why This Is Better Than Nested Loops

  • Readability: Anyone reading the code can immediately tell you're transforming each parent item into its child items while merging relevant fields.
  • Conciseness: No need for manual loop setup or pushing items into a new array—flatMap() handles the flattening automatically.
  • Immutability: This approach creates a new array without altering the original data, which is a best practice in modern JavaScript development.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:15:02