在对象内搜索对象并获取密钥

问题描述 投票:0回答:3

我有一个如下所示的目标路由器。可以说我还有另一个var x = "/podcast",我想找到此变量x将驻留在哪个键上。例如,在这种情况下,我想返回值“ M2”

如何搜索此对象路由器及其子对象以返回适当的密钥?

谢谢!

var router = {
  M1: {
    url: "/",
    description: "",
    title: "",
    image: "",
  },
  M2: {
    url: "/podcast",
    description: "",
    title: "",
    image: "",
  },
  M3: {
    url: "/about",
    description: "",
    title: "",
    image: "",
  },
};
javascript object search
3个回答
1
投票

您可以使用Object.keys()获取对象键数组,然后单击Object.keys(),这是一个有效的代码段:


0
投票

使用查找来找到匹配的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

0
投票
  • 要获取密钥,请使用.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
© www.soinside.com 2019 - 2024. All rights reserved.