javascript 使用FlatMap/Map向每个对象添加父属性

iyfamqjs  于 2023-01-16  发布在  Java
关注(0)|答案(4)|浏览(156)

我试图用几行代码实现以下结果。
预期结果:

[{
  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)
vmjh9lq9

vmjh9lq91#

上面贝赫拉姆和Ori的问题是生成的索引不正确;它将产生1,2,3,1,2,3:
而是从Map器中删除索引值:

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

console.log(result)
cx6n0qe3

cx6n0qe32#

首先,您需要另一个.map来将每个城市与其国家联系起来。

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

console.log(aa)

你也可以考虑命令式版本,虽然功能不太强大,但更容易理解。

const obj = [
    {
      country: "USA",
      cities: ["California", "New York", "Austin"]
    },
    {
      country: "Russia",
      cities: ["Moscow", "kazan", "Samara"]
    }
  ];
const aa = [];
let id = 1;
for (const { cities, country } of obj) {
  for (const name of cities) {
    aa.push({ name, country, id: id++, active: true });
  }
}
console.log(aa)
afdcj2ne

afdcj2ne3#

function transform(obj) {
      let id = 0;
      return obj.flatMap(({country, cities}) => cities.map(city => ({active:true, name: city, country,id: ++id})))
  }
  
 console.log(transform(obj))

如果需要一行程序,可以将id存储在父匿名函数中(但我不建议这样做,因为这样可读性较差)

console.log(((id) => obj.flatMap(({country, cities}) => cities.map(city => ({active:true, name: city, country,id: ++id}))))(0))
tzdcorbm

tzdcorbm4#

按照以下方式:

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

相关问题