问题
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.valuesUse
findto get specific value by doingidcomparisonGet
nameproperty 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