0

Following is an example of js object:

var arr =          
{
      "a1": { "0.25": 13, "0.5": 50},
      "a2": { "0.5": 50, "0.75": 113, "1": 202}
}

id = 'a1';
key = "0.25";

function myFunc(id, key) {
  return arr[id][key];
}

Using the above function I can get the value of the corresponding key.

My question how can I get the Key for a given value?

E.g. if id = 'a2' and value = 113, the function should return the corresponding key 0.75

ravi
  • 1,078
  • 2
  • 17
  • 31
  • Have a look at this answer to the same question: https://stackoverflow.com/questions/9907419/how-to-get-a-key-in-a-javascript-object-by-its-value – flppv Mar 16 '19 at 03:26
  • It’s important to note that this is not a multidimensional array. There are no arrays in your code. This is an object where each key is a string and the values are objects. An array would be `[1,2,3]`. – Nate Mar 16 '19 at 03:27
  • I agree it's not an array but its an Object. thanks for correcting and thank you all for the help. – ravi Mar 16 '19 at 03:34

3 Answers3

1

You can get keys for arr[a] first and than filter key based on value

var arr ={"a1": { "0.25": 13, "0.5": 50},"a2": { "0.5": 50, "0.75": 113, "1": 202}}

let a = 'a1',val = 13;

let getKey = (a,val) =>  Object.keys(arr[a]).filter(e => arr[a][e] === val)

console.log(getKey(a,val))
console.log(getKey('a2',113))

If you're sure that there's always one key with matching value or you want the first matching values key only than you can use find instead of filter

var arr ={"a1": { "0.25": 13, "0.5": 50},"a2": { "0.5": 50, "0.75": 113, "1": 202}}

let a = 'a1',val = 13;

let getKey = (a,val) =>  Object.keys(arr[a]).find(e => arr[a][e] === val)

console.log(getKey(a,val))
console.log(getKey('a2',113))
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
1

You can use Object.entries to get the key

var arr = {
  "a1": {
    "0.25": 13,
    "0.5": 50
  },
  "a2": {
    "0.5": 50,
    "0.75": 113,
    "1": 202
  }
}

function myFunc(a, key) {
  var k = Object.entries(arr[a]).flat();
  return k[k.indexOf(key) - 1]
}
console.log(myFunc('a1', 13))
ellipsis
  • 12,049
  • 2
  • 17
  • 33
0

Use Object.entries() and Array#find

var arr ={"a1": { "0.25": 13, "0.5": 50},"a2": { "0.5": 50, "0.75": 113, "1": 202}}

var a = 'a2',val = 113;

var Key = (a,val) =>  Object.entries(arr[a]).find(i=> i[1] == val)[0];

console.log(Key(a,val))
prasanth
  • 22,145
  • 4
  • 29
  • 53
  • On Side note:- It's worth mentioning that find will give only the first matching value's key. if there are more than one matching value's it won't return all the keys – Code Maniac Mar 16 '19 at 03:38
  • @CodeManiac .Op not mention multiple matching – prasanth Mar 16 '19 at 03:39