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

For example, I know value of 1. I need to get that object's name with its value. var x = {quest: "blah blah blah", answers: ["1812", "1837", "1864", "1899"], correct: "1837"}

returnNameOf(x) expected output 1;

Kim Ber
  • 69
  • 11

3 Answers3

1

You can use find() on Object.keys() and compare objects using 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));
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
0

You can convert the object to string and use in comparison. So in this example we need to find the key whose value matches with toMatch. Therefore in the function toMatch is converted to string since object matching or object equality test will return false as they compare memory location

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))
brk
  • 48,835
  • 10
  • 56
  • 78
0

You could search in the Objects entries:

const key = 0, value = 1;

const result = Object.entries(questions).find(it => it[value] === x)[key];
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151