0

Loop through the Object and filter by key. obj is the object I have to loop through and filter it by the given key and obtain its value alone

If the given key to filter is 'chem' then the expected result is:

{
    name: 'Luke Skywalker',
    title: 'Jedi Knight',
    age: 23,

}

I have a solution. But it's not very efficient. Looking for a better way to address this.

const obj = {
  chem: {
    name: 'Luke Skywalker',
    title: 'Jedi Knight',
    age: 23,
  },
  history: {
    name: 'Anakin Skywalker',
    title: 'Jedi Knight',
    age: 18,
  },
  bio: {
    name: 'Yoda',
    title: 'Jedi master',
    age: 50,
  }
};
const asArray = Object.entries(obj);

const filtered = asArray.filter(([key, value]) => key === 'chem');
console.log(filtered[0][1]);
dragonfly
  • 3,203
  • 7
  • 30
  • 52
  • `obj['chem']` has O(1) – evolutionxbox Sep 12 '22 at 23:48
  • const asArray = Object.entries(obj); const filtered = asArray.filter(([key, value]) => key === 'chem'); console.log(filtered[0][1]); instead of above thry below for(const key in obj){ if(key==='chem'){ console.log(obj[key]) } } – Rahman Aliyev Sep 13 '22 at 01:10

0 Answers0