Reputation: 1524
I'm getting the JSON response as below:-
{
"links":{
"self":"https://xyz/v1/test/1/attributes"
},
"data":[
{
"type":"tenantFields",
"id":1,
"attributes":{
"field_name":"firstName",
"is_required":false,
"is_sync_enabled":true
},
"relationships":{
},
"links":{
"self":"https://xyz/v1/test/1/attributes/1"
}
},
{
"type":"tenantFields",
"id":2,
"attributes":{
"field_name":"lastName",
"is_required":false,
"is_sync_enabled":true
},
"relationships":{
},
"links":{
"self":"https://xyz/v1/test/1/attributes/2"
}
},
{
"type":"tenantFields",
"id":3,
"attributes":{
"field_name":"userTitle",
"is_required":false,
"is_sync_enabled":false
},
"relationships":{
},
"links":{
"self":"https://xyz/v1/test/1/attributes/3"
}
}
],
"included":[
]
}
Before performing any operation, I need to apply the filter based on is_sync_enabled to true (ignore all from the array where the value for is_sync_enabled is false) and then read only the field_name attribute value from the filtered JSON data.
Please suggests, thanks
Upvotes: 0
Views: 863
Reputation: 30675
You can use a combination of Array.filter and Array.map to get the desired output.
We'd use Array.filter to get the desired elements, looking for those with attributes and attributes with the .is_sync_enabled property set.
We can then use Array.map to pick the attributes.field_name property.
let input = { "links":{ "self":"https://xyz/v1/test/1/attributes" }, "data":[ { "type":"tenantFields", "id":1, "attributes":{ "field_name":"firstName", "is_required":false, "is_sync_enabled":true }, "relationships":{ }, "links":{ "self":"https://xyz/v1/test/1/attributes/1" } }, { "type":"tenantFields", "id":2, "attributes":{ "field_name":"lastName", "is_required":false, "is_sync_enabled":true }, "relationships":{ }, "links":{ "self":"https://xyz/v1/test/1/attributes/2" } }, { "type":"tenantFields", "id":3, "attributes":{ "field_name":"userTitle", "is_required":false, "is_sync_enabled":false }, "relationships":{ }, "links":{ "self":"https://xyz/v1/test/1/attributes/3" } } ], "included":[ ] };
let output = input.data.filter(element => {
return (element.attributes && element.attributes.is_sync_enabled);
}).map(element => {
return element.attributes.field_name;
});
console.log("Output:", output);
Upvotes: 3