Answer the question
In order to leave comments, you need to log in
How to get an element of an object in nodejs?
There is a very large object. Its element keys are not known. It is necessary to obtain as efficiently as possible (in time) one key of any of its elements. What is the best way to do this?
Answer the question
In order to leave comments, you need to log in
It doesn't matter if it's a node or not.
There are two options:
1. Search.
2. Build a reverse index, where the keys and values are swapped.
There may be a case where several keys have the same values, so you need to keep an array of keys for each element of the index.
var data = {
key1: "value1",
key2: "value2",
key3: "value1",
key4: "value2",
key5: "value3"
};
var index = {};
for (var key in data) {
var value = data[key];
if (index[value]) index[value].push(key);
else index[value] = [key];
}
console.dir(index);
{ value1: [ 'key1', 'key3' ],
value2: [ 'key2', 'key4' ],
value3: [ 'key5' ] }
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question