0

Let's say I have this data set as

let data = {
  1: ['item1', '3435'],
  32: ['item2', '5465'],
  16: ['item3', '6577']
}

Now I want to find the key which contains the number "3435". For this, I could not find out a way to iterate over objects. Is there any way to find a match without using iteration?

findKey(3534) // should return "1"
findKey(6577) // should return "16"
Ivar
  • 6,138
  • 12
  • 49
  • 61
geek glance
  • 111
  • 2
  • 9

5 Answers5

1

Maybe you can iterate like this. Not sure if we can achieve this without iteration.

const getKey = (matchString) => {
  let data = {
    1: ['item1', '3435'],
    32: ['item2', '5465'],
    16: ['item3', '6577']
  }

  for (let item in data) {
    if (data[item].includes(matchString)) {
      return item;
    }
  }
}

const key = getKey('3435')
console.log(key)
Mehul Thakkar
  • 2,177
  • 13
  • 22
1

A possible solution would be:

 let data = {
  1 : ['item1', '3435'],
  32 : ['item2', '5465'],
  16 : ['item3', '6577']
}

for (const [key, value] of Object.entries(data)) {  
  if(value.includes('3435'))  
  {
    console.log(key)
  }
}
Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79
0

You can't iterate directly over a JSON, but you can get the list of keys with Object.keys().

From there, they are two choices:

If you know there is only one value matching use a loop to return the selected one

function findInObject(value) {
  for (let i in Object.keys(data)) {
    if (data[i][1] == value) {
      return i
    }
  }
}

returns 16.

If there may be more than one entry use filter()

function findInObject(value) {
  return Object.keys(data.filter(elem => elem[1] == value))
}

returns [16, 42, 1000].

Andy
  • 61,948
  • 13
  • 68
  • 95
SteeveDroz
  • 6,006
  • 6
  • 33
  • 65
0

function searchByKey(data,Sval){
  let output
  Object.entries(data).forEach(each=>{
    let key = each[0] , val = each[1][1]
    if(Sval == val){output = each[0]}
  })
  return output
}
 
 
let data = {
    1 : ['item1', '3435'],
    32 : ['item2', '5465'],
    16 : ['item3', '6577']
  }

let s = searchByKey(data,"5465")

console.log(s)
Note this function is specific to your current data structure only
Amir Rahman
  • 1,076
  • 1
  • 6
  • 15
0

You may leverage Object.entries() method to retrieve key.

const data = {
  1: ["item1", "3435"],
  32: ["item2", "5465"],
  16: ["item3", "6577"]
};

const getMatchingKey = (num) => {
  return Object.entries(data).filter(([key, value]) => value[1] === num)[0];
  // if you need all matching keys, remove the 0th index ===============^^^
};

const [key] = getMatchingKey("3435");
console.log(key);
Andy
  • 61,948
  • 13
  • 68
  • 95
Vinay Sharma
  • 3,291
  • 4
  • 30
  • 66