Home > Enterprise >  How to find particular id using iterate Object in JavaScript
How to find particular id using iterate Object in JavaScript

Time:03-28

i'm trying to iterate this object with the help of for each How to find particular id using iterating object and supposed we want to

if(id == 12) {
   return true;
}else{
   return false;
}

This is a object

const data = {
    "service": [
        "BUSINESS",
        "LEGAL",
        "FINANCE",
        "ADVERTISEMENT"
    ],
    "service1": [
        { "id": 1 },
        { "id": 2 },
        { "id": 3 },
        { "id": 4 },
    ],
    "service2": [
        { "id": 5 },
        { "id": 6 },
        { "id": 7 },
        { "id": 8 },
    ],
    "service3": [
        { "id": 9 },
        { "id": 10 },
        { "id": 11 },
        { "id": 12 },
    ],
    "service4": [
        { "id": 13 },
        { "id": 14 },
        { "id": 15 },
        { "id": 16 },
    ],
}

CodePudding user response:

First, you check iterated object structure. If it contains array of object's or array of string's. Then find an object with ID which you need.

const data = {
  service: ["BUSINESS", "LEGAL", "FINANCE", "ADVERTISEMENT"],
  service1: [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }],
  service2: [{ id: 5 }, { id: 6 }, { id: 7 }, { id: 8 }],
  service3: [{ id: 9 }, { id: 10 }, { id: 11 }, { id: 12 }],
  service4: [{ id: 13 }, { id: 14 }, { id: 15 }, { id: 16 }]
};

Object.entries(data).forEach(([_, value]) => {
  if (value.every((item) => typeof item === "object")) {
    if (value.find((item) => item.id === 12)) {
      // do your action
    } 
  }
});

  • Related