如何通过其值[JS]

时间:2019-03-11 17:16:38

标签: javascript oop

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;

3 个答案:

答案 0 :(得分:1)

您可以在find()上使用Object.keys(),并使用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));

答案 1 :(得分:0)

您可以将对象转换为字符串并进行比较。因此,在此示例中,我们需要找到其值与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))

答案 2 :(得分:0)

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

const key = 0, value = 1;

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