Reputation: 169
In my angular app. I get response from an Api. The Api response is in the Json APi format with include and relationships. I have saved the data with included and Relationships in a variable. I am trying to find a particular 'type' and fetch the variable and assign it to local variable. How can i achieve this. Please guide me.
Note. How can i access the value of key "level" in included.
TS
this.testService.gettestdata(id).subscribe((data: any) => {
this.testdata = data;
const swords_level = data.included // what can i do here to fetch the level value from "included" > type = skills > attributes > level.
});
testdata (format of my json response saved in variable.)
{
"data": [{
"type": "characters",
"id": "1",
"attributes": {},
"relationships": {
"skills": {
"data": [{
"type": "skills", "id": "swords"
}, {
"type": "skills", "id": "bows"
}]
},
"descriptions": {
"data": [{
"type": "skill-descriptions", "id": "swords"
}, {
"type": "skill-descriptions", "id": "bows"
}]
},
}
}
}],
"included": [{
"type": "skills",
"id": "swords",
"attributes": {
"level": 20
}
}, {
"type": "skills",
"id": "bows",
"attributes": {
"level": 3
}
},{
"type": "skill-descriptions",
"id": "swords",
"attributes": {
"name": "Swords",
"description": "Fighting with swords",
"help": "This skill influences the ability to fight using a sword, both in terms of the ability to hit your opponent and to block any incoming attacks from them.",
"icon": "http://localhost:8080/icons/skills/swords.png"
}
},{ ...
}]
}
Upvotes: 0
Views: 77
Reputation: 31125
You could use array filter
method on the included
array and filter based on the type
and id
properties. And access the attributes.level
property.
Note: I assume you'll have unique elements for type
and id
combinations. If not the resulting array will have multiple elements and I am accessing the level
property of only the first element.
var input = {
"included": [{
"type": "skills",
"id": "swords",
"attributes": {
"level": 20
}
}, {
"type": "skills",
"id": "bows",
"attributes": {
"level": 3
}
}]
};
var output = input.included
.filter(item => item.type === "skills" && item.id === "swords")[0]
.attributes.level;
console.log(output)
Upvotes: 2