Reputation: 119
I have an array of objects in Javascript:
[
{a: 1, b: 2, c: 4},
{d: 10, a: 9, r: 2},
{c: 5, e: 2, j: 41}
]
I would like to return an array of all the objects that have the key name c
by using the key name for the lookup.
What is the best way to accomplish this?
Upvotes: 1
Views: 1206
Reputation: 231
.filter
+ in
operator
var arr = [
{a: 1, b: 2, c: 4},
{d: 10, a: 9, r: 2},
{c: 5, e: 2, j: 41}
];
var result = arr.filter((x) => 'c' in x);
console.log(result)
Upvotes: 1
Reputation: 443
the easiest way is to loop through the array to check if the object has a key named c
var arr = [
{ a: 1, b: 2, c: 4 },
{ d: 10, a: 9, r: 2 },
{ c: 5, e: 2, j: 41 }
]
// they both do the same job
var result = arr.filter(item => Object.keys(item).some(key => key === 'c'))
var filtered = arr.filter(item => item.hasOwnProperty('c'))
console.log(result);
console.log(filtered);
Upvotes: 0
Reputation: 136
You can use filter method and hasOwnProperty
const arr = [{a: 1, b: 2, c: 4},{d: 10, a: 9, r: 2},{c: 5, e: 2, j: 41}];
const myArray = array.filter(e => e.hasOwnProperty('c'))
Upvotes: 2
Reputation: 27192
You can simply achieve this by using Array.filter()
method along with Object.hasOwn()
.
Live Demo :
const arr = [
{a: 1, b: 2, c: 4},
{d: 10, a: 9, r: 2},
{c: 5, e: 2, j: 41}
];
const res = arr.filter(obj => Object.hasOwn(obj, 'c'));
console.log(res);
Upvotes: 0
Reputation: 19251
use filter()
, and maybe hasOwnProperty()
or another way to check if the property is present on the object.
const myarray = [
{ a: 1, b: 2, c: 4 },
{ d: 10, a: 9, r: 2 },
{ c: 5, e: 2, j: 41 }
];
const processedarray = myarray.filter( item => item.hasOwnProperty( 'c' ) );
console.log( processedarray );
Upvotes: 0
Reputation: 1179
Try using filter and hasOwnProperty.
const data = [{
a: 1, b: 2, c: 4
},
{
d: 10, a: 9, r: 2
},
{
c: 5, e: 2, j: 41
}
];
const filtered = (arr, prop) =>
arr.filter(a => a.hasOwnProperty(prop));
console.log(
JSON.stringify(filtered(data, 'c'))
);
If you want to return an array of objects with multiple specific keys, you can combine it with some.
const data = [{
a: 1, b: 2, c: 4
},
{
d: 10, a: 9, r: 2
},
{
c: 5, e: 2, j: 41
}
];
const filtered = (arr, ...props) =>
arr.filter(a => props.some(prop => a.hasOwnProperty(prop)));
console.log(
JSON.stringify(filtered(data, 'b', 'j'))
);
Upvotes: 0
Reputation: 94
This is My answer. Thank you
const arr = [
{a: 1, b: 2, c: 4},
{d: 10, a: 9, r: 2},
{c: 5, e: 2, j: 41}
]
const filter = (arr, byKey) => {
return arr.filter((ob) => {
return Object.keys(ob).includes(byKey)
})
}
console.log(filter(arr, 'c'))
Upvotes: -1