I have a response: Response body:
[ { "id": "6094f8253e2bf70001827add", "name": "groupdk2502", "type": "One", }, { "id": "5f7ae257c64bb7000168175a", "name": "Badminton Vejle", "type": "Group", }, { "id": "5f76c43cec5fdeb57baa0c31", "name": "Nl-golf Vejle", "type": "Group", }, { "id": "5f7ae258c64bb7000168176f", "name": "Schaatsen Vejle", "type": "Group", }, { "id": "5f7ae258c64bb70001681775", "name": "Bridge Vejle", "type": "Group", } ]
I receive an array with 5 objects. I want to set the variable for the first object within “type”: “Group”. attachment image. But I don’t know the way. Does anyone help me???
Advertisement
Answer
What you’re looking for is .find
which returns the first occurrence matching a predicate or undefined. For example:
data.find(x => x.type === "Group");
See the example below
const data = [ { "id": "6094f8253e2bf70001827add", "name": "groupdk2502", "type": "One", }, { "id": "5f7ae257c64bb7000168175a", "name": "Badminton Vejle", "type": "Group", }, { "id": "5f76c43cec5fdeb57baa0c31", "name": "Nl-golf Vejle", "type": "Group", }, { "id": "5f7ae258c64bb7000168176f", "name": "Schaatsen Vejle", "type": "Group", }, { "id": "5f7ae258c64bb70001681775", "name": "Bridge Vejle", "type": "Group", } ]; const first = data.find(x => x.type === "Group"); console.log(first);