Recently we had a very basic requirement to delete an key value pare in the json array using Javascript.
Input data
{"invideoPromotion":{"items":[{"id":{"type":"video","videoId":"11","websiteUrl":""},"timing":{"type":"ms","offsetMs":"2222"},"customMessage":"aa","promotedByContentOwner":"vanji"}]}}
Expected business logic
When type of id is video and websiteUrl is null; websiteUrl should be removed from the payload.
Output data
{"items":[{"id":{"type":"video","videoId":"11"},"timing":{"type":"ms","offsetMs":"2222"},"customMessage":"aa","promotedByContentOwner":"vanji"}]}}
In-order to do this you can use delete functionality of the json in javascript.
Example code
Input data
{"invideoPromotion":{"items":[{"id":{"type":"video","videoId":"11","websiteUrl":""},"timing":{"type":"ms","offsetMs":"2222"},"customMessage":"aa","promotedByContentOwner":"vanji"}]}}
Expected business logic
When type of id is video and websiteUrl is null; websiteUrl should be removed from the payload.
Output data
{"items":[{"id":{"type":"video","videoId":"11"},"timing":{"type":"ms","offsetMs":"2222"},"customMessage":"aa","promotedByContentOwner":"vanji"}]}}
In-order to do this you can use delete functionality of the json in javascript.
Example code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script> | |
var text = '{"invideoPromotion":{"items":[{"id":{"type":"video","videoId":"11","websiteUrl":""},"timing":{"type":"ms","offsetMs":"2222"},"customMessage":"aa","promotedByContentOwner":"vanji"}]}}' | |
var obj = JSON.parse(text); | |
document.writeln(JSON.stringify(obj)); | |
for (var i = 0; i < obj.invideoPromotion.items.length; i++) { | |
if (obj.invideoPromotion.items[i].id.type == 'video') { | |
if (obj.invideoPromotion.items[i].id.websiteUrl == '') { | |
delete obj.invideoPromotion.items[i].id.websiteUrl; | |
} | |
} | |
} | |
document.writeln(JSON.stringify(obj)); | |
</script> |
No comments:
Post a Comment