简体   繁体   中英

Getting name of parent object from value of object

This feels really simple, but I couldn't find a straightforward answer.

I have an object:

var obj = {
        'John': {'phone':'7326', 'age': '23'},
        'Paul': {'phone': '9898', 'age': '12'},
        'Lucy': {'phone': '1122', 'age': '24'}
}

I have the phone number 9898. How do I get 'Paul' as the result?

Just use Object.keys() and find()

 var obj = { 'John': {'phone':'7326', 'age': '23'}, 'Paul': {'phone': '9898', 'age': '12'}, 'Lucy': {'phone': '1122', 'age': '24'} } const res = Object.keys(obj).find(e => obj[e].phone === '9898'); console.log(res); 

You could use find method on Object.entries .

 var obj = {'John': {'phone':'7326', 'age': '23'},'Paul': {'phone': '9898', 'age': '12'},'Lucy': {'phone': '1122', 'age': '24'}} var [name] = Object.entries(obj).find(([_, {phone}]) => phone == 9898) || [] console.log(name) 

You can try either of these:-

for(var key in obj){
   if(obj[key].phone == "9898") {
      console.log(key);
   }
}

or

const key= Object.keys(obj).find(e => obj[e].phone === '9898');
console.log(key);

Do with Object.keys and array find:

 var obj = { 'John': {'phone':'7326', 'age': '23'}, 'Paul': {'phone': '9898', 'age': '12'}, 'Lucy': {'phone': '1122', 'age': '24'} }; var phone_to_search = '9898'; var result = Object.keys(obj).find(current=>{ if (obj[current]['phone']===phone_to_search) return current; }); console.log(result); 

 var obj = { 'John': {'phone':'7326', 'age': '23'}, 'Paul': {'phone': '9898', 'age': '12'}, 'Lucy': {'phone': '1122', 'age': '24'} } let givenPhone = '9898' let userName = 'UNKNOWN'; Object.entries(obj).forEach(([user, {phone}])=> { if(phone === givenPhone) userName = user; }) console.log(userName) 

It's better to create a function, this way you can reuse the code. This code goes though the object and compare the phone until it finds a coincidence.

var obj = {
    'John': {'phone':'7326', 'age': '23'},
    'Paul': {'phone': '9898', 'age': '12'},
    'Lucy': {'phone': '1122', 'age': '24'}
}

function searchPhone(obj, phone){
  for(var key in obj){
    if(obj[key]['phone'] == phone){
        return key
      }
  }
}

console.log(searchPhone(obj, '9898'))

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