node.js - Javascript: Check whether key exists in an array of objects -


var _ = require('lodash');  var users = [   { 'id': '1', 'coins': false },   { 'id': '2', 'coins': false } ];  var = _.every(users, function(p){   if ('id' in p && 'coins' in p)     return true;   else     return false; }); console.log(a); 

the function works check in keys exists in array of objects. if 1 of object doesn't exists "id" or "coins" , return false.

is there better way write thie snippet of code? felt quite clumsy.

since you're in node.js, know have array.every() don't see reason lodash here or 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, code assuming nobody has mysteriously added properties named id or coins object.prototype (which seems safe assumption here). if wanted protect against that, use item.hasownproperty('id') instead of in.


Comments

Popular posts from this blog

java - Date formats difference between yyyy-MM-dd'T'HH:mm:ss and yyyy-MM-dd'T'HH:mm:ssXXX -

c# - Get rid of xmlns attribute when adding node to existing xml -