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?
CodePudding user response:
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.indexOf('c') > -1))
var filtered = arr.filter(item => item.hasOwnProperty('c'))
console.log(result);
console.log(filtered);
CodePudding user response:
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'))
);
CodePudding user response:
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 );
CodePudding user response:
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)
CodePudding user response:
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'))