繁体   English   中英

如何通过值[JS]获取对象的属性名称

[英]How can I get object's property name by its value [JS]

questions={
     1:{
          quest: "blah blah blah",
          answers: ["1812", "1837", "1864", "1899"],
          correct: "1837"
     },
     2:{
         quest: "fasfa asf",
         answers : ["2","3","4","5"],
         correct : "3"
     }
 }

例如,我知道1值。 我需要获取该对象的名称及其值。 var x = {quest: "blah blah blah", answers: ["1812", "1837", "1864", "1899"], correct: "1837"}

returnNameOf(x)预期输出1

您可以在Object.keys() find()上使用find()并使用JSON.stringify()比较对象

 let questions={ 1:{ quest: "blah blah blah", answers: ["1812", "1837", "1864", "1899"], correct: "1837" }, 2:{ quest: "fasfa asf", answers : ["2","3","4","5"], correct : "3" } } let val = { quest: "fasfa asf", answers : ["2","3","4","5"], correct : "3" } function getKey(obj,value){ if(typeof value === "object"){ value = JSON.stringify(value); return Object.keys(obj).find(key => JSON.stringify(obj[key]) === value); } else return Object.keys(obj).find(key => obj[key] === value); } console.log(getKey(questions,val)); 

您可以将对象转换为字符串并进行比较。 因此,在此示例中,我们需要找到其值与toMatch匹配的键。 因此,在函数toMatch其转换为字符串,因为对象匹配或对象相等性测试在比较内存位置时将返回false

 let toMatch = { quest: "blah blah blah", answers: ["1812", "1837", "1864", "1899"], correct: "1837", }; let questions = { 1: { quest: "blah blah blah", answers: ["1812", "1837", "1864", "1899"], correct: "1837" }, 2: { quest: "fasfa asf", answers: ["2", "3", "4", "5"], correct: "3" } } function findKey(objString) { let val = JSON.stringify(toMatch) for (let keys in questions) { if (JSON.stringify(questions[keys]) === val) { return keys; } } } console.log(findKey(toMatch)) 

您可以在“对象”条目中搜索:

const key = 0, value = 1;

const result = Object.entries(questions).find(it => it[value] === x)[key];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM