0

lets say I have object like this:

{
1: [1,2,3],
2: [4,6,7],
3: [5, 8,9,10]
etc..
}

Now i want to get value and a key by value. So my input would be: 5 and I need to get key and value of a object that contains that 5, so it is 3:[5,8,9,10] in the example above. The key is important just like value of a object. Is there a method for that in JS? Something like Includes on arrays or I need to loop throu it? What if object has like 10k keys?

Faker22
  • 15
  • 5
  • You can access it like this: `obj['5']`. – Ibu Nov 05 '20 at 21:17
  • I did a mistake and I fixed that already. The thing is I don't know they key. Only value is known. – Faker22 Nov 05 '20 at 21:18
  • You can look through object properties using `for(var i in obj)`. So `i` is the property name, and the value (an array in your case is `obj[i]`. So loop through and check if it contains your value. – Ibu Nov 05 '20 at 21:20
  • Check this one https://stackoverflow.com/a/5072145/1880380 – Mindastic Nov 05 '20 at 21:22

2 Answers2

4

What if object has like 10k keys?

You will have to iterate over all keys/properties, there is no way around this. Array#includes does that too, just internally.

A simple solution would be combining Object.keys with Array#find:

const result = Object.keys(obj).find(key => obj[key].includes(value));
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
0

You can use Object.entries(). This code will return also more objects that contain the search value.

const obj = {
  1: [1, 2, 3],
  2: [4, 6, 7],
  3: [5, 8, 9, 10],
  4: [5, 11, 19, 110]

}


const res = {}
for (const [key, value] of Object.entries(obj)) {
  value.includes(5) ? res[key] = value : null;
}

console.log(res);
MWO
  • 2,627
  • 2
  • 10
  • 25