Javascript/Lodash/Redux-从对象返回具有特定ID的对象 [英] 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"},
...
}
并使用lodash get函数将特定名称保存为常量.
and using lodash get function I want to save specific name into constant.
const name = _.get(state, ['names', nameId]);
我知道这将不起作用,因为我正在选择对象的键而不是ID.知道如何解决吗?请注意,我无法像使用id作为对象的键那样规范化数据,因为它破坏了那些数据来自BE的顺序.是否可以遍历对象并查找特定的id?
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 ?
我正确地从其他功能获得了nameId
I'm getting the nameId
correctely from other function
推荐答案
无需Lodash.只需遍历对象的属性,以查找id
上的匹配项:
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);
或者使用Object.keys
和some
,但是除了跳过继承的属性外,它实际上并不会给您带来其他好处:
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);
或使用ES2017的 Object.values
(对于较旧的环境很容易填充)和find
:
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);
这篇关于Javascript/Lodash/Redux-从对象返回具有特定ID的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!