【问题标题】:Add Parent Property to each Objects using FlatMap/Map使用 FlatMap/Map 为每个对象添加父属性
【发布时间】:2023-01-15 14:47:09
【问题描述】:

我试图在几行代码中实现以下结果。

预期结果:

[{
  active: true,
  id: 1,
  name: "California",
  country: USA
}, {
  active: true,
  id: 2,
  name: "New York",
  country:"USA"
},...
 {
  active: true,
  id: 4,
  name: "Moscow",
  country:"Russia"
}, ....]

这是我尝试过的,但结果中再次缺少一个属性country。期望以最短且有效的方式实现这一目标。谢谢你的回复。

 const obj = [
    {
      country: "USA",
      cities: ["California", "New York", "Austin"]
    },
    {
      country: "Russia",
      cities: ["Moscow", "kazan", "Samara"]
    }
  ];
 
//here the map of country is not there, wondering how to achieve this.
//obj.map(y => y.country).flatMap(x => x.cities)
const aa = obj.flatMap(x => x.cities)
   .map((str, index) => ({ name: str, id: index + 1, active:true}));

console.log(aa)

【问题讨论】:

    标签: javascript typescript


    【解决方案1】:

    提取countrycities,映射cities以创建对象并包含country

    const obj = [{"country":"USA","cities":["California","New York","Austin"]},{"country":"Russia","cities":["Moscow","kazan","Samara"]}];
    
    const result = obj.flatMap(({ country, cities }) => 
      cities.map((str, index) => ({
        name: str,
        country,
        id: index + 1,
        active: true
      }))
    );
    
    console.log(result)

    【讨论】:

      【解决方案2】:

      按照这种方式:

      const results = obj.flatMap(({ country, cities }) => {
          return cities.map((city, index) => ({
              active: true,
              id: index + 1,
              name: city,
              country: country
          }));
      });
      console.log(results);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-11-27
        • 2014-12-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多