简体   繁体   中英

How can I compare values between objects in an array?

I've been scratching my head for a long time with this one, even tough it feels like an easy task. I have an array with a set of objects. The array looks like this:

[ { key1: 'ok', key2: 'ok', key3: '--' },
  { key1: 'ok', key2: '--', key3: 'ok' },
  { key1: 'ok', key2: 'ok', key3: '--' } ]

I want a function that compares the objects, and returns the key that has all "ok" as it's value. In this case, I'd like it to return

key1

I've been watching Compare objects in an array for inspiration, but it just doesn't do it.

Do anyone have any suggestions? Would be a life saver

You could iterate the array and filter the keys.

 var array = [{ key1: 'ok', key2: 'ok', key3: '--' }, { key1: 'ok', key2: '--', key3: 'ok' }, { key1: 'ok', key2: 'ok', key3: '--' }], result = array.reduce(function (r, o) { return r.filter(function (k) { return o[k] === 'ok'; }); }, Object.keys(array[0])); console.log(result); 

ES6

 var array = [{ key1: 'ok', key2: 'ok', key3: '--' }, { key1: 'ok', key2: '--', key3: 'ok' }, { key1: 'ok', key2: 'ok', key3: '--' }], result = array.reduce((r, o) => r.filter(k => o[k] === 'ok'), Object.keys(array[0])); console.log(result); 

Most likely not the shortest solution, but should be easy to follow..

 var obj = [ { key1: 'ok', key2: 'ok', key3: '--' }, { key1: 'ok', key2: '--', key3: 'ok' }, { key1: 'ok', key2: 'ok', key3: '--' } ]; var keycount = {}; obj.forEach((o) => { Object.keys(o).forEach((key) => { if (o[key] === 'ok') keycount[key] = (keycount[key] || 0) + 1; }); }); Object.keys(keycount).forEach((key) => { if (keycount[key] === obj.length) console.log(`Found ${key}`); }); 

Assuming all objects have identical keys:

  for (var key in arr[0]){
     var allok = true;
     for (var i = 0; i < arr.length; i++){
        if (arr[i][key] !== "ok") {
           allok = false;
           break;
        }
     }
     if (allok) {console.log(key);}
  }

Here's what I would do:

 var objs = [ { key1: 'ok', key2: 'ok', key3: '--' }, { key1: 'ok', key2: '--', key3: 'ok' }, { key1: 'ok', key2: 'ok', key3: '--' } ]; var getOkKeys = function(objs) { return Object.keys(objs[0]).reduce(function(results, key) { if (objs.every(function(obj) { return (obj[key] === 'ok'); })) { results.push(key); } return results; }, []); }; console.log(getOkKeys(objs)); 

As requested, a function that returns the keys - getOkKeys() .

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