I have an array of objects that I want to filter based on the name of the key for those objects. In this particular case I know that there will be one key/value pair for each element in the array.
Assume an array that looks like this:
let dataArray = [
{
"name": "David"
},
{
"location": "New York"
},
{
"name": "Jenna"
}
]
What I want to end up with is just an array where the key is 'name':
[
{
name: "David"
},
{
name: "Jenna"
}
]
I've tried various ways of doing this using the filter method, such as this:
const namesArr = dataArr.filter(i => i[key] === 'name');
But none seem to produce the correct result.
Use the in operator to check if a property exists on the object:
const dataArray = [{"name":"David"},{"location":"New York"},{"name":"Jenna"}];
// name exists on the object
console.log(dataArray.filter(item => 'name' in item));
// or location doesn't exist on the object
console.log(dataArray.filter(item => !('location' in item)));
You can use the object.hasOwnProperty('name') that returns a boolean indicating whether object has a property name
let dataArray = [
{
"name": "David"
},
{
"location": "New York"
},
{
"name": "Jenna"
}
]
const filtered = dataArray.filter(x => x.hasOwnProperty('name'));
console.log(filtered);
another option is to use the in operator:
let dataArray = [
{
"name": "David"
},
{
"location": "New York"
},
{
"name": "Jenna"
}
]
const filtered = dataArray.filter(x => 'name' in x);
console.log(filtered);