删除包含重复属性的嵌套对象

时间:2019-02-12 17:38:59

标签: javascript

我在这里有一个嵌套对象

{ people: {
    bob: {
      city: 'florida',
      phone: '561-482-2234'
    },
    jen: {
      city: 'florida',
      phone: '407-382-3883'
    },
    kim: {
      city: 'new york',
      phone: '607-321-3003'
    }
}}

我需要过滤该对象,以便不存在重复的城市-最终结果将是包含bob&kim的对象。我不关心顺序还是对象中剩下两个佛罗里达人,因此可以是jen&kim

我当前的实现包含一个for循环,该循环遍历人员,存储临时键并在名称与临时键匹配的情况下删除嵌套对象。我觉得这是一个漫长而漫长的解决方案

是否存在可以实现此目的的ES6方法?

2 个答案:

答案 0 :(得分:2)

您可以使用Set过滤键并删除此键。

var a = { people: { bob: { city: 'florida', phone: '561-482-2234' }, jen: { city: 'florida', phone: '407-382-3883' }, kim: { city: 'new york', phone: '607-321-3003' } } };

Object
    .keys(a.people)
    .filter((s => k => s.has(a.people[k].city) || !s.add(a.people[k].city))(new Set))
    .forEach(k => { delete a.people[k]; });

console.log(a);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:1)

使用减少

var a = {
  people: {
    bob: {
      city: 'florida',
      phone: '561-482-2234'
    },
    jen: {
      city: 'florida',
      phone: '407-382-3883'
    },
    kim: {
      city: 'new york',
      phone: '607-321-3003'
    }
  }
};
Object.keys(a.people).reduce((acc, e) => {
acc.includes(a.people[e].city) ? delete a.people[e] : acc.push(a.people[e].city);
  return acc
}, [])
console.log(a)

使用forEach循环

var a = {
  people: {
    bob: {
      city: 'florida',
      phone: '561-482-2234'
    },
    jen: {
      city: 'florida',
      phone: '407-382-3883'
    },
    kim: {
      city: 'new york',
      phone: '607-321-3003'
    }
  }
};
var cities = [];
Object.keys(a.people).forEach((e) => {
  if (cities.includes(a.people[e].city))
    delete a.people[e];
  else
    cities.push(a.people[e].city);
})
console.log(a)