我有一个如下所示的目标路由器。可以说我还有另一个var x = "/podcast"
,我想找到此变量x将驻留在哪个键上。例如,在这种情况下,我想返回值“ M2”
如何搜索此对象路由器及其子对象以返回适当的密钥?
谢谢!
var router = {
M1: {
url: "/",
description: "",
title: "",
image: "",
},
M2: {
url: "/podcast",
description: "",
title: "",
image: "",
},
M3: {
url: "/about",
description: "",
title: "",
image: "",
},
};
您可以使用Object.keys()
获取对象键数组,然后单击Object.keys()
,这是一个有效的代码段:
使用查找来找到匹配的url属性。.filter()
创建[[key,value],...]条目的列表。使用const search = '/podcast';
const router = {
M1: {
url: "/",
description: "",
title: "",
image: ""
},
M2: {
url: "/podcast",
description: "",
title: "",
image: ""
},
M3: {
url: "/about",
description: "",
title: "",
image: ""
}
};
const foundElement = Object.keys(router).filter((el) => router[el].url === search);
console.log(foundElement[0]);
查找url属性的第一个匹配项。 (解构值的url属性,并与x匹配)。使用[0]获取密钥。
Object.entries
.find
var router = {
M1: {
url: "/",
description: "",
title: "",
image: ""
},
M2: {
url: "/podcast",
description: "",
title: "",
image: ""
},
M3: {
url: "/about",
description: "",
title: "",
image: ""
}
};
var x = "/podcast"
console.log(
Object.entries(router).find(([,{url}])=>url===x)[0]
)
,可以使用Object.keys(object)
或key
。 filter()
或find()
中定义callback
功能。就我而言,我使用了filter
函数:
find