I have an array of objects being returned to me as data
, I'm looking to Create a new set of data, while retaining the old one for future use.
I'm trying to loop through the data given to create a new set of data that only contains age, but also removes any duplicates. I'm not too sure where to start with this.
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"
}
]
What I'd like to end up with is something like this:
newData = [
{"age": "99"},
{"age": "50"},
{"age": "22"}
]
Or you can just use Set
for eliminating duplicates:
// 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 }));
Wow, so many approaches, Here is another one: purely functional:
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);
}
});
You can use .map
and .filter
combined with a Set for this:
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.