简体   繁体   中英

Get the object with more properties from an array of objects

Assuming I have the following array in a JSON file:

[
    { id: 1 },
    { name: 'foo' },
    { id: 3, name: 'foo', nick: 'bar' },
    { id: 4, nick: 'next' },
    { nick: 'nextnext' }
]

How to get the object with more properties? In this example I should get the third item: { id: 3, name: 'foo', nick: 'bar' }

If there is another object with 3 properties, I can get two results or the last found, it doesn't matter, my purpose is to know all properties an object can have.

To cope with multiple results, you could use filter.

 var data = [ { id: 1 }, { name: 'foo' }, { id: 3, name: 'foo', nick: 'bar' }, { id: 4, nick: 'next' }, { nick: 'nextnext' }, { id: 6, name: 'another 3', nick: '3'} ] const mx = Math.max(...data.map(m => Object.keys(m).length)); const res = data.filter(f => Object.keys(f).length === mx) console.log(res); 

You can use reduce and Object.keys() to return the object which has more length.

Try the following way:

 var data = [ { id: 1 }, { name: 'foo' }, { id: 3, name: 'foo', nick: 'bar' }, { id: 4, nick: 'next' }, { nick: 'nextnext' } ] var res = data.reduce((a, c) => { return Object.keys(a).length > Object.keys(c).length ? a : c; }) console.log(res); 

You can create an array and put values based on key length.

Since you want objects with most keys, you can get the last item.

 var data = [ { id: 1 }, { name: 'foo' }, { id: 3, name: 'foo', nick: 'bar' }, { id: 4, nick: 'next' }, { nick: 'nextnext' } ]; var res = data.reduce((a, c) => { const len = Object.keys(c).length; a[len] = a[len] || []; a[len].push(c); return a; }, []).pop(); console.log(res); 

let biggestObj = {};

for(let el of array){
    if(Object.keys(el).length > Object.keys(biggestObj).length){
        biggestObj = el;
    }
}

This should do the job!

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