简体   繁体   中英

Finding this key exist in object or not without loop in js

I have object a and object b .I want to check key of b exist in a or not without using loop how can I do this.

var a = {name1: "hello", game1: "no games", name2: "world"}
var b = {name1:'hello world'}

Yes I can do this using loop. First I can get all the keys of b in array and i can take each key at a time and find by using .hasOwnProperty() but I am looking for the method without using loop how is it possible.

Try this:

 var a = {name1: "hello", game1: "no games", name2: "world"}; var b = {name1:'hello world'}; var exists = Object.keys(a).includes(Object.keys(b)[0]) console.log(exists); 

In case there are multiple keys in b to ckeck in a, it should be:

 var a = {name1: "hello", game1: "no games", name2: "world"}; var b = {name1:'hello world', game1: "no games"}; var exists = Object.keys(b).every(bKey => Object.keys(a).includes(bKey)); console.log(exists); 

Or just:

 var a = {name1: "hello", game1: "no games", name2: "world"}; var b = {name1:'hello world', game1: "no games"}; var exists = Object.keys(b).every(bKey => bKey in a); console.log(exists); 

If the keys are not known in advance (and there can be more than one key to check), you can use this trick:

  var a = {name1: "hello", game1: "no games", name2: "world"} var b = {name1:'hello world'} // Extract keys from a var keysA = Object.keys(a); // For each key from b, check if a includes it // See [1] if needed for every() console.log( Object.keys(b).every(function(k) { return keysA.includes(k); }) ); 

Admittedly, this is very similar to using a loop.

[1] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every

You can also try underscore.js function _.findKey(object, predicate=_.identity])

Example:-
var users = {
  'barney':  { 'age': 36, 'active': true },
  'fred':    { 'age': 40, 'active': false },
  'pebbles': { 'age': 1,  'active': true }
};

_.findKey(users, function(o) { return o.age < 40; });

Output => 'barney' (iteration order is not guaranteed)

最简单的方法是:

 console.log('game1' in {name1: "hello", game1: "no games", name2: "world"}) 

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