简体   繁体   中英

Return all nested objects with specific keys

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?

.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)

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 );

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')) );

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);

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);

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'))

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'))

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM