Home > Mobile >  Filter an Object and Return Key in Typescript
Filter an Object and Return Key in Typescript

Time:11-30

I have an object to be filtered and it should return a key that has a specific id. Id is Unique . Need an efficient logic to return this expected output.The Object to be filtered.

{
  "a":[{"id":"1123","value":"test1"}],
  "b":[{"id":"1124","value":"test2"}],
  "c":[{"id":"1125","value":"test3"}]
  
}

Input Id: "1124"

Expected Output  : 'b'

CodePudding user response:

let data  = {
  "a":[{"id":"1123","value":"test1"}],
  "b":[{"id":"1124","value":"test2"}],
  "c":[{"id":"1125","value":"test3"}]
};

let input = "1124";

let result  = Object.entries(data).filter(([k,v]) => v[0].id === input)[0][0];
console.log(result);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Efficiencies here:

  • break the loop as soon as something is found
  • not interested in the object that has the id, only in checking that something there has that id

o = {
  "a":[{"id":"1123","value":"test1"}],
  "b":[{"id":"1124","value":"test2"}],
  "c":[{"id":"1125","value":"test3"}]
  
}
for (key in o) {
  if (o[key].some(x => x.id === '1124')) {
    console.log(key);
    break;
  }
}
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

const input = "1124"

const obj = {
  "a":[{"id":"1123","value":"test1"}],
  "b":[{"id":"1124","value":"test2"}],
  "c":[{"id":"1125","value":"test3"}]  
}

Object.values(obj).filter((ob, i)=>{if(ob[0].id === input){console.log(Object.keys(obj)[i])}})
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related