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

半世苍凉 提交于 2019-12-10 18:50:04

问题


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


回答1:


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);



回答2:


You can use _.find() with _.values() to get specific object by id.

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

var r = _.find(_.values(state.names), {id: 1})
console.log(r)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>



回答3:


Try this simple approach

var output = Object.values( obj.names ).find( function( item ){ return item.id = inputId }).name;
  • Iterate the object values' array by using Object.values

  • Use find to get specific value by doing id comparison

  • Get name property of the returned object.

Demo

var obj = {
    names: {
        0: {"id": 30, name: "Adam"},
        1: {"id": 1, name: "Ben"},
        2: {"id": 15, name: "John"}
    }
};   
var inputId = 15;
console.log( Object.values( obj.names ).find( function( item ){ return item.id = inputId }).name );


来源:https://stackoverflow.com/questions/47012147/javascript-lodash-redux-return-object-with-specific-id-from-an-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!