简体   繁体   中英

Javascript: Check whether key exists in an array of objects

var _ = require('lodash');

var users = [
  { 'id': '1', 'coins': false },
  { 'id': '2', 'coins': false }
];

var a = _.every(users, function(p){
  if ('id' in p && 'coins' in p)
    return true;
  else
    return false;
});
console.log(a);

The function works to check in keys exists in an array of objects. If one of the object doesn't exists "id" or "coins" , it return false.

Is there a better way to write thie snippet of code? I felt quite clumsy.

Since you're in node.js, you know you already have array.every() so I don't see any reason for lodash here or for the if/else . Why not this:

var users = [
  { 'id': '1', 'coins': false },
  { 'id': '2', 'coins': false }
];

var allValid = users.every(function(item) {
    return 'id' in item && 'coins' in item;
});

FYI, this code is assuming nobody has mysteriously added properties named id or coins to the Object.prototype (which seems like a safe assumption here). If you wanted to protect against that, you could use item.hasOwnProperty('id') instead of in .

At very least, replace:

if ('id' in p && 'coins' in p)
    return true;
else
    return false;

With:

return 'id' in p && 'coins' in p;

Basically, never use a construct like:

if (x)
    return true;
else
    return false;

x is already a boolean, or at least a truthy / falsy value.

In case you need to be sure the returned value is a boolean, just force it to one:

return !!('id' in p && 'coins' in p);

Also, as mentioned in the other answer, lodash is redundant, here. You canuse JS's native [every][3] .
Replace:

_.every(users, function(p){

With:

users.every(function(p){

You can use _.has() to check if an object property exists:

function checkValidity(array, listOfKeys) {
    return _.every(array, function (item) {
        return _.every(listOfKeys, function (key) {
            return _.has(item, key);
        });
    });
}

Usage:

checkValidity(users, ['id', 'coins']);

I'd use the [Array.prototype.some()][1] function:

 var users = [
  { 'id': '1', 'coins': false },
  { 'id': '2', 'coins': false }
];


    var result = users.some(e => e.hasOwnProperty('id') && e.hasOwnProperty('coins'));

    console.log("The array contains an object with a 'name' and 'quantity' property: " + result);

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