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"
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)
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)
}
}
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].