ES6-仅使用一个属性从现有数据中创建新对象,并删除任何重复项?

时间:2019-10-06 18:55:58

标签: javascript arrays ecmascript-6

我有一组对象以data的形式返回给我,我希望创建一组新数据,同时保留旧数据以备将来使用。

我正在尝试遍历给定的数据以创建一组新数据,该数据集不仅包含年龄,而且还删除了所有重复项。我不太确定从哪里开始。

data = [
    {
        "firstName": "John",
        "lastName": "Doe",
        "age": "99"
    }, 
    {
        "firstName": "Jimmy",
        "lastName": "Hendricks",
        "age": "50"
    }, 
    {
        "firstName": "William",
        "lastName": "Shakespeare",
        "age": "22"
    }, 
    {
        "firstName": "Jane",
        "lastName": "Eyre",
        "age": "50"
    }
]

我最终想得到的是这样的东西:

newData = [
        {"age": "99"}, 
        {"age": "50"}, 
        {"age": "22"}
]

4 个答案:

答案 0 :(得分:2)

或者您也可以使用Set来消除重复项:

// ages variable contain just the ages
const ages = data.map(person => person.age);
// new Set(ages) will remove duplicated values:
const newSet = Array.from(new Set(ages)).map(age => ({ age: age }));

答案 1 :(得分:2)

哇,方法太多了! 这是另一个纯粹的功能:

data = [ { "firstName": "John", "lastName": "Doe", "age": "99" }, { "firstName": "Jimmy", "lastName": "Hendricks", "age": "50" }, { "firstName": "William", "lastName": "Shakespeare", "age": "22" }, { "firstName": "Jane", "lastName": "Eyre", "age": "50" } ]; 

console.log(
 Object.keys(data.reduce((obj,o)=>
 	    (obj[o.age]=1,obj),{}))
.map(k=>({age:k}))
)

答案 2 :(得分:1)

let newData = [];
let uniques = [];
data.forEach(el => {
    if(!uniques.includes(el.age)){
      newData.push({age: el.age});
      uniques.push(el.age);
}
});

答案 3 :(得分:1)

您可以将.map.filterSet结合使用:

const data = [
    {
        "firstName": "John",
        "lastName": "Doe",
        "age": "99"
    }, 
    {
        "firstName": "Jimmy",
        "lastName": "Hendricks",
        "age": "50"
    }, 
    {
        "firstName": "William",
        "lastName": "Shakespeare",
        "age": "22"
    }, 
    {
        "firstName": "Jane",
        "lastName": "Eyre",
        "age": "50"
    }
]

const newdata = data
  .map(({age}) => ({age})) // convert `{age: <value of age>}`
  .filter(function({age}) {
    const isUnique = !this.has(age); //check if already present
    this.add(age); //add anyway

    return isUnique; //filter keeping uniques
  }, new Set());//use a Set as the `this` context for the filter
  
console.log(newdata);