在键值对的规范化对象中查找具有给定值的对象
Find object with given value in normalized object of key value pairs
假设我有一个标准化对象(正如您在使用 redux 时经常看到的那样)包含如下键值对:
const normalized_object = {
"1": {
id: "1",
color: "red",
other_id: "45"
},
"2": {
id: "2",
color: "blue",
other_id: "101"
},
"3": {
id: "3",
color: "green",
other_id: "77"
}
};
检索具有给定 other_id
的内部对象的最佳方法是什么。类似于以下内容:
const inner_obj = normalized_object.find(entry => entry.other_id === "77");
console.log(inner_obj);
// Prints the third inner object with id "3"
有单线的吗?
您可以使用 Object.values
:
const normalized_object = {
"1": { id: "1", color: "red", other_id: "45" },
"2": { id: "2", color: "blue", other_id: "101" },
"3": { id: "3", color: "green", other_id: "77" }
};
const inner_obj = Object.values(normalized_object).find(entry => entry.other_id === "77");
console.log(inner_obj);
假设我有一个标准化对象(正如您在使用 redux 时经常看到的那样)包含如下键值对:
const normalized_object = {
"1": {
id: "1",
color: "red",
other_id: "45"
},
"2": {
id: "2",
color: "blue",
other_id: "101"
},
"3": {
id: "3",
color: "green",
other_id: "77"
}
};
检索具有给定 other_id
的内部对象的最佳方法是什么。类似于以下内容:
const inner_obj = normalized_object.find(entry => entry.other_id === "77");
console.log(inner_obj);
// Prints the third inner object with id "3"
有单线的吗?
您可以使用 Object.values
:
const normalized_object = {
"1": { id: "1", color: "red", other_id: "45" },
"2": { id: "2", color: "blue", other_id: "101" },
"3": { id: "3", color: "green", other_id: "77" }
};
const inner_obj = Object.values(normalized_object).find(entry => entry.other_id === "77");
console.log(inner_obj);