简体   繁体   English

Javascript:检查键是否存在于对象数组中

[英]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. 如果对象之一不存在“ id”或“ coins”,则返回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 . 由于您位于node.js中,因此您知道您已经拥有array.every()因此在这里看不到lodash或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). 仅供参考,此代码假定没有人神秘地将名为idcoins属性添加到Object.prototype(在这里似乎是一个安全的假设)。 If you wanted to protect against that, you could use item.hasOwnProperty('id') instead of in . 如果您想防止这种情况,可以使用item.hasOwnProperty('id')代替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. x已经是一个布尔值,或者至少是一个true / falsy值。

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. 另外,如另一个答案中所述,lodash在这里是多余的。 You canuse JS's native [every][3] . 您可以使用JS的本机[every][3]
Replace: 更换:

_.every(users, function(p){

With: 附:

users.every(function(p){

You can use _.has() to check if an object property exists: 您可以使用_.has()检查对象属性是否存在:

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: 我会使用[Array.prototype.some()] [1]函数:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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