Home > Enterprise >  How to loop object and get value from an object
How to loop object and get value from an object

Time:09-02

I have a question about how to loop an object in typescript and to get the value that I want.

my object looks like this:

mockdata = {

 "subobj1": {
   "order": 1
   "value": "abc"
 },
 "subobj2": {
   "order": 2
   "value": "aaa"
 },
  ...


}

I want to loop this object and only get the subobject, if order == 1

what I expect is to get object

"subobj1": {
   "order": 1
   "value": "abc"
 }

any solutions?

CodePudding user response:

Just loop through the object using for in syntax and find the respective value!

const mockdata = {

  "subobj1": {
    "order": 1,
    "value": "abc"
  },
  "subobj2": {
    "order": 2,
    "value": "aaa"
  },

}
let output;
for (const property in mockdata) {
  if (mockdata[property].order === 1) {
    output = {
      [property]: mockdata[property]
    }
    break;
  }
}


console.log('result', output);

CodePudding user response:

Here's a pretty slim way to do it. I usually use Object.keys or .entries to all my obj for loops

const arrOfOrderEqualToOne = Object.entries(mockdata).filter(([key, value]) => value.order === 1));

CodePudding user response:

Try this

    let mockdata = {

 "subobj1": {
   "order": 1,
   "value": "abc"
 },
 "subobj2": {
   "order": 2,
   "value": "aaa"
 },
}
let temp;
Object.keys(mockdata).forEach(key=>{
  if(mockdata[key].order==1){
    temp=mockdata[key]
  }
})

console.log(temp)
  • Related