代码之家  ›  专栏  ›  技术社区  ›  s7vr

用父值展平数组

  •  0
  • s7vr  · 技术社区  · 8 年前

    鉴于

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

    我试图将数据展平为表格式,将值数组中的每个对象作为一个表行,并复制父字段。

    后果

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

    我想提及哪些字段要与父字段隔离。对于ex single field,即我们示例中的country field。其他示例可能包括多个或所有父字段。

    有没有一种优雅的方法可以达到预期的效果?现在,我正在使用嵌套for循环来实现同样的效果。

    1 回复  |  直到 8 年前
        1
  •  1
  •   intentionally-left-nil    8 年前

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

    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);