Reputation: 6347
I hae the following array of objects:
arr = [
{
name: "john",
age: 24,
gender: "male"
},
{
name: "jane",
age: 27,
gender: "female"
},
{
name: "joe",
age: 29,
gender: "male"
}
]
I'm trying to filter the name
and age
property into a new array. I tried this:
const newFields = arr.filter((item) => {
return (
item.name && item.age
);
});
But for some reason newFields
returns an empty array.
Upvotes: 0
Views: 1810
Reputation: 56
This can be a one liner too with the arrow function and Parameter Context Matching
const newFields = arr.map(({ name, age }) => ({ name, age }));
Your solution's result can not be empty but the original array, because in this case the return value of your filter
function will be always true (every item has the name and age property) which doesn't filter anything from the original arr
variable.
Upvotes: 2
Reputation: 944
Instead of .filter()
use .map()
const arr = [
{
name: "john",
age: 24,
gender: "male"
},
{
name: "jane",
age: 27,
gender: "female"
},
{
name: "joe",
age: 29,
gender: "male"
}
];
const newFields = arr.map(item => {
return {
name: item.name,
age: item.age
}
});
console.log(newFields)
Upvotes: 2
Reputation: 15519
If you are creating a new array with a subset of the original - then you can iterate over the array and push the desired elements into its own array.
That said if all you are trying to get is the name and age of the existing array - why do you need to create a separate array? - you can just iterate over the original array and reference only the desired values from each item.
let arr = [
{
name: "john",
age: 24,
gender: "male"
},
{
name: "jane",
age: 27,
gender: "female"
},
{
name: "joe",
age: 29,
gender: "male"
}
]
let newArr = [];
arr.forEach(function(item) {
newArr.push({name:item.name, age:item.age})
});
console.log(newArr); // gives [{"name": "john","age": 24},{"name": "jane","age": 27},{"name": "joe","age": 29}]
Upvotes: 0