简体   繁体   English

如何在 Javascript 中 map 数组 Object

[英]How to map an array of Object in Javascript

I am stuck with mapping in array of objects.我被困在对象数组中的映射。 Please find the below code请找到以下代码

const array = [
  {
    user: "User1",
    cities: ["city1", "city2", "city3"],
  },
  {
    user: "User2",
    cities: ["city2", "city3", "city4"],
  },
];

let x = {};

array.map((item) => {
  let user = item.user;
  let cities = item.cities;
  cities.map((city) => (x[city] = user));
});

Now it returns like this:现在它像这样返回:

const resArray = [{ city1: "User1", city2: "User2", city3: "User2", city4: "User2" }]

I want the array like this:我想要这样的数组:

const resArray = [
  { city1: ["User1"] },
  { city2: ["User1", "User2"] },
  { city3: ["User1", "User2"] },
  { city4: ["User2"] },
];

Can anyone please help me out.谁能帮帮我。

Thanks谢谢

Try this尝试这个

let x = {};
array.forEach((item) => {
  item.cities.forEach((city) => {
    x[city] = item.cities.includes(city) ? [...x[city] ? x[city] : [], item.user] : [];
  });
});

You have been assigning user to city each time.您每次都将用户分配到城市。 Instead the x[city] should be an array and you should push the new user inside that array.相反, x[city] 应该是一个数组,您应该将新用户推送到该数组中。

Try this,尝试这个,

const array = [
  {
    user: "User1",
    cities: ["city1", "city2", "city3"],
  },
  {
    user: "User2",
    cities: ["city2", "city3", "city4"],
  },
];

let x = {};

array.map((item) => {
  let user = item.user;
  let cities = item.cities;
  cities.map((city) => {
    if(x[city] && x[city].length) {
      x[city].push(user);
    } else{
      x[city] = [user];
    }
  });
});

const res = Object.keys(x).map(key => { return {[key]: x[key]}});
console.log(res);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM