Home > front end >  Is there a better way to find the field of an object with a value of this object?
Is there a better way to find the field of an object with a value of this object?

Time:10-03

I'm looking for a better way to do the following:

obj = {
    "1111": {"name": "Peter", "descr": "....."},
    "2222": {"name": "Alex", "descr": "....."},
    "3333": {"name": "Tom", "descr": "....."}
};

function getUserIdBy(field, value, object) {
    var res;
    Object.keys(object).forEach(id => {
        if (object[id][field] === value) res = id;
    })
    return res;
}

console.log(getUserIdBy('name', 'Tom')); // return a string : "3333"

CodePudding user response:

Thanks for your answers, I found that :

function getCharacterIdBy(field, value, object) {
    return Object.keys(object).filter(id => object[id][field] === value)
}

And I will look to change my object to an array.

CodePudding user response:

You can use also this solution:

function getUserIdBy(field, value, object) {
  for (var id in object) {
    if (object[id][field] === value) {
      return id;
    }
  }
}

getUserIdBy('name', 'Peter', obj); // 1111
getUserIdBy('name', 'Tom', obj); // 3333
getUserIdBy('name', 'Alex', obj); // 2222
getUserIdBy('name', 'Bob', obj); // undefined
  • Related