简体   繁体   中英

How to apply filter on JSON response?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM