benl134
benl134

Reputation: 134

Passing in the key and returning the object javascript

With a JSON array structured like this one,

"object1": {
  "key1": "value1"
  "key2": "value2"
}
"object2": {
  "key3": null
  "key4": null
}
}

Could I pass in the key eg. key3 and get returned the object it is part of eg. object2?

I know this would be possible with a for loop, but I have a lot of keys so I am wondering if there is another way.

Upvotes: 0

Views: 58

Answers (2)

Unmitigated
Unmitigated

Reputation: 89214

You can iterate over all of the keys and create a lookup table. This would allow searching in O(1) after incurring the preprocessing cost.

const obj = {
  "object1": {
    "key1": "value1",
    "key2": "value2"
  },
  "object2": {
    "key3": null,
    "key4": null
  }
};
const lookup = {};
for (const k of Object.keys(obj)) {
  for (const k2 of Object.keys(obj[k])) {
    lookup[k2] = k;
  }
}
console.log(lookup['key3']);
console.log(obj[lookup['key3']]);
console.log(lookup['key1']);

Upvotes: 2

aligumustosun
aligumustosun

Reputation: 152

let json = {
  "object1": {
    "key1": "value1",
    "key2": "value2"
  },
  "object2": {
    "key3": null,
    "key4": null
  }
};
let keyToLookFor = "key3";
Object.entries(json).forEach(([key,entry]) => { 
  if(Object.keys(entry).includes(keyToLookFor)) { 
    console.log(json[key]) 
  } 
})

Upvotes: 1

Related Questions