[英]ES6 - Create new object from existing data, using only one property, and removing any duplicates?
我有一組對象作為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"}
]
或者您可以只使用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 }));
哇,這么多方法,這是另一種方法:純功能:
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})) )
let newData = [];
let uniques = [];
data.forEach(el => {
if(!uniques.includes(el.age)){
newData.push({age: el.age});
uniques.push(el.age);
}
});
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.