After parsing the JSON data, you will receive an array with either two objects for the first style or one string entry. Here is the code snippet to handle this:
function processJSON(data) {
let parsedData = JSON.parse(data);
if (typeof parsedData.phoneNumber[0] === "object") {
parsedData.phoneNumber = [parsedData.phoneNumber.find(obj => obj.add).add[0]];
}
console.log(parsedData);
}
Here is a live example of how to use the function:
function processJSON(data) {
let parsedData = JSON.parse(data);
if (typeof parsedData.phoneNumber[0] === "object") {
parsedData.phoneNumber = [parsedData.phoneNumber.find(obj => obj.add).add[0]];
}
console.log(parsedData);
}
processJSON('{"phoneNumber":[{"remove":["0099887769"]},{"add":["0099887765"]}]');
processJSON('{"phoneNumber":["0099887765"]}');
If you require an ES5 version, here it is:
function processJSON(data) {
var parsedData = JSON.parse(data);
if (typeof parsedData.phoneNumber[0] === "object") {
parsedData.phoneNumber = [parsedData.phoneNumber.find(function(obj) { return obj.add; }).add[0]];
}
console.log(parsedData);
}