提问者:小点点

要基于包含数组项的对象属性映射的数组


如果我有一个像下面这样的对象

result  = [
 {
   phones : ["ABC", "DEF"],
   name: "Simon"
 },
 {
   phones : ["ABC", "XZY"],
   name: "John"
 }
]

预期产出

键值映射

{ABC,     ["Simon", "John"]}
{DEF,     ["Simon"]}
{XYZ,     ["John"]}

我的尝试

map: Map = new Map();   
for ( r of result ) {
   for( phone of r.phones) {
      if(map.get(phone)){
        map.put(phone, map.get(phone).concat(r.name))
      } else {
        map.put(phone, r.name);
      }
   }
}

那么有没有ES6的方式来执行上述功能呢?


共2个答案

匿名用户

使用Array.Prototype.Reduce,可以做到这一点。

null

const input = [{
  phones: ["ABC", "DEF"],
  name: "Simon"
},
{
  phones: ["ABC", "XZY"],
  name: "John"
}];

const result = input.reduce((acc, cur) => {
  cur.phones.forEach((item) => {
    acc[item] ? acc[item].push(cur.name) : acc[item] = [ cur.name ];
  });
  return acc;
}, {});
console.log(result);

匿名用户

我不知道ES6够不够用,但是使用map-reduce给出了这样的东西:

result.reduce((map, person) => {
  person.phones.forEach(phone => 
    map.has(phone)
      ? map.get(phone).push(person.name)
      : map.set(phone, [person.name])
  );
  return map;
}, new Map());

但是代码或多或少是相同的,性能可能也不是那么差,而可读性则是读者的眼睛。

总之,你的里程可能会有所不同。