[英]How to apply filter on JSON response?
I'm getting the JSON response as below:-我收到 JSON 响应如下:-
{
"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.在执行任何操作之前,我需要将基于is_sync_enabled的过滤器应用为true (从 is_sync_enabled 值为 false 的数组中忽略所有),然后从过滤的 JSON 数据中仅读取field_name属性值。
Please suggests, thanks请推荐,谢谢
You can use a combination of Array.filter and Array.map to get the desired output.您可以使用Array.filter和Array.map的组合来获得所需的 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.我们将使用 Array.filter 来获取所需的元素,寻找那些具有属性和具有 .is_sync_enabled 属性集的属性。
We can then use Array.map to pick the attributes.field_name property.然后我们可以使用 Array.map 来选择 attributes.field_name 属性。
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.