0

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 },
    ],
}

1 Answer 1

1

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
    } 
  }
});

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.