使用父值展平数组

Flatten array with parent values

给定

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

我正在尝试将数据扁平化为 table 格式,将值数组中的每个对象作为一个 table 行,父字段重复。

结果

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

我想提一下要从父字段中保留哪些字段。对于前单个字段,即我们示例中的国家/地区字段。其他示例可能包括多个或所有父字段。

有什么优雅的方法可以达到预期的效果吗?现在我正在使用嵌套的 for 循环来实现相同的目的。

它最终是两个嵌套循环,但您可以利用 mapreduce 来简化代码。见下文:

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

const result = input.reduce((output, {country, values}) =>
  output.concat(values.map(({city}) => ({ country, city }))), []);
  
console.log(result);