0

We are getting JSON string two ways:

"{"phoneNumber":[{"remove":["0099887769"]},{"add":["0099887765"]}]}"

Or

"{"phoneNumber":["0099887765"]}"

We have to convert "{"phoneNumber":[{"remove":["0099887769"]},{"add":["0099887765"]}]}" in "{"phoneNumber":["0099887765"]}" way

Is there any way to write a JavaScript to determine which JSON has "add" key and which one don't have.

Zoe
  • 27,060
  • 21
  • 118
  • 148
Indranil Banerjee
  • 133
  • 1
  • 1
  • 11
  • You can use `Object.hasOwnProperty(key)` method or simply `if(object.key){}` – Ninad Nov 11 '18 at 13:16
  • JSON is a *textual notation* for data exchange. [(More here.)](http://stackoverflow.com/a/2904181/157247) If you're dealing with JavaScript source code, and not dealing with a *string*, you're not dealing with JSON. So by the time you're doing this check, you're not dealing with JSON anymore, you'll have parsed it. – T.J. Crowder Nov 11 '18 at 13:18

6 Answers6

1

When you parse the JSON, you'll have an array with two entries (each objects) if it's the first style, or an array with one entry that's a string. So:

function handle(theJSON) {
    let parsed = JSON.parse(theJSON);
    if (typeof parsed.phoneNumber[0] === "object") {
        parsed.phoneNumber = [parsed.phoneNumber.find(o => o.add).add[0]];
    }
    console.log(parsed);
}

Live Example:

function handle(theJSON) {
    let parsed = JSON.parse(theJSON);
    if (typeof parsed.phoneNumber[0] === "object") {
        parsed.phoneNumber = [parsed.phoneNumber.find(o => o.add).add[0]];
    }
    console.log(parsed);
}
    
handle('{"phoneNumber":[{"remove":["0099887769"]},{"add":["0099887765"]}]}');

handle('{"phoneNumber":["0099887765"]}');

Or if you need an ES5 version:

function handle(theJSON) {
    var parsed = JSON.parse(theJSON);
    if (typeof parsed.phoneNumber[0] === "object") {
        parsed.phoneNumber = [parsed.phoneNumber.find(function(o) { return o.add; }).add[0]];
    }
    console.log(parsed);
}
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • We might get the json : "{"email":[{"remove":["ind@gmail.com"]},{"add":["indra2121@gmail.com"]}]}" – Indranil Banerjee Nov 11 '18 at 16:28
  • @IndranilBanerjee - Just generalize the above. If you need to discover the name of the one property in the wrapper (which suggests a design issues somewhere), you can get it from `Object.keys(parsed)[0]`. – T.J. Crowder Nov 11 '18 at 16:36
  • Actually from a third party application, I am getting different types of json. – Indranil Banerjee Nov 11 '18 at 17:13
  • @IndranilBanerjee - If your code doesn't know, by the nature of the API it's calling, what the shape of the result is, that's a design error -- in the API you're calling. – T.J. Crowder Nov 11 '18 at 17:15
  • Actually from a third party application, I am getting different types of json. Example : To modify phone number I am getting json: '{"phoneNumber":[{"add":["0099844465"],"remove":["0099887769"]},{"add":["0099887765"]}]}' for update email : {"email":[{"remove":["ind@gmail.com"]},{"add":["indra2121@gmail.com"]}]}" For add user: {"username":["user1"],"password":["pass@123"],"email":["ind2121@gmail.com"]} I need determine the operation and make a common json like: {"attribute":"value"} I have no control on third party API/application. – Indranil Banerjee Nov 11 '18 at 17:18
  • @IndranilBanerjee - Right, so again, you'd do it as in the comment above. It's unfortunate you have to deal with an API that makes you do that. – T.J. Crowder Nov 11 '18 at 17:20
  • Is there any way to find "add" is there or not in a json keys. for two types of JSON: {"username":["user1"],"password":["pass@123"],"email":["ind2121@gmail.com"]} or {"phoneNumber":[{"add":["0099844465"],"remove":["0099887769"]},{"add":["0099887765"]}]} so I can do it. Thank you for your support. – Indranil Banerjee Nov 11 '18 at 17:57
  • 1
    @IndranilBanerjee - I told you how to do it [several comments ago](https://stackoverflow.com/questions/53249069/check-a-key-on-a-json-object/53249166?noredirect=1#comment93386462_53249166). – T.J. Crowder Nov 12 '18 at 08:22
0

You can use some to return true/false if "add" is a property on any object in the array. Here's a general solution:

const json = '{"phoneNumber":[{"remove":["0099887769"]},{"add":["0099887765"]}]}';
const data = JSON.parse(json);

function checkForKey(data, { arrayKey, searchKey }) {
  return data[arrayKey].some(obj => obj[searchKey]);
}

const hasAdd = checkForKey(data, {arrayKey: 'phoneNumber', searchKey: 'add' });
console.log(hasAdd);
Andy
  • 61,948
  • 13
  • 68
  • 95
0

You can do it by using for..in loop and hasOwnProperty check, finally push only the phoneNumbers with add index. Hope this helps :)

const expected = {'phoneNumber':[]};
let str = '{"phoneNumber":[{"add":["0099844465"],"remove":["0099887769"]},{"add":["0099887765"]}]}';

const st_obj = JSON.parse(str);
for (var k in st_obj['phoneNumber']) {
        if (st_obj['phoneNumber'][k].hasOwnProperty('add'))           {
           expected['phoneNumber'].push(st_obj['phoneNumber'][k]['add']);
        }
}

console.log(expected);
A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103
-1

just check if add is top level propery

if(obj['add']) {....}

if it is exists then if will be true, if not it will return undefined and if will be false,

if you should check it in array of objects, you can use the same logic with find method from array prototype

phoneNumber.find(obj => obj['add']);
Artyom Amiryan
  • 2,846
  • 1
  • 10
  • 22
-1

You can check whether the add key exists by converting the JSON into array:

How to convert JSON object to JavaScript array

With that you are able to check if the key exists by checking whether the key is undefined:

obj["phonenumber"]["add"] != undefined
Momondo
  • 306
  • 1
  • 2
  • 10
-1

use let obj = JSON.parse('{"phoneNumber":[{"remove":["0099887769"]},{"add":["0099887765"]}]}') to convert it to object. then iterate it and fetch value and push it into new object