Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript/Lodash/Redux - return object with specific id from an object

So lets say we have an object:

names:
    {
     0: {"id": 30, name: "Adam"},
     1: {"id": 1, name: "Ben"},
     2: {"id": 15, name: "John"},
     ...
    }

and using lodash get function I want to save specific name into constant.

const name = _.get(state, ['names', nameId]);

I know this will not work because I'm selecting the key of the object not the id. Any idea how to fix it ? Note that I can't normalize the data like use the id as a key of the object because it ruins the order in which those data come from BE. Is it possible to loop through the object and look for the specific id ?

I'm getting the nameId correctely from other function

like image 218
Hayk Shakhbazyan Avatar asked Aug 05 '26 15:08

Hayk Shakhbazyan


1 Answers

No need for Lodash. Just loop through the object's properties looking for a match on id:

const names = {
 0: {"id": 30, name: "Adam"},
 1: {"id": 1, name: "Ben"},
 2: {"id": 15, name: "John"}
};
const nameId = 1;
let obj;
for (const name in names) {
  if (names[name].id == nameId) {
    obj = names[name];
    break;
  }
}
console.log(obj);

Or using Object.keys and some, but it doesn't really buy you anything other than skipping inherited properties:

const names = {
 0: {"id": 30, name: "Adam"},
 1: {"id": 1, name: "Ben"},
 2: {"id": 15, name: "John"}
};
const nameId = 1;
let obj;
Object.keys(names).some(name => {
  if (names[name].id == nameId) {
    obj = names[name];
    return true;
  }
});
console.log(obj);

Or using ES2017's Object.values (which is easily polyfilled for older environments) and find:

const names = {
 0: {"id": 30, name: "Adam"},
 1: {"id": 1, name: "Ben"},
 2: {"id": 15, name: "John"}
};
const nameId = 1;
const obj = Object.values(names).find(entry => entry.id == nameId);
console.log(obj);
like image 118
T.J. Crowder Avatar answered Aug 07 '26 06:08

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!