I have to parse a json object that can be a string, array, array of strings and array of object. I realised that it's not good from the beginning that one object can be many types, but I can't change the code from upstream so I'll have to deal it in my code instead. I'm building a pixel library for modern browser so I'm not using jQuery or lodash. I'm supporting most modern browser and IE >= 9
Here's the example of the data that can be returned
"author": {
"@type": "Person",
"name": "Author"
}
Or
"author":[{"@type":"Person","name":"Author"}]
Or
"author": 'Author'
Or
"author": ['Author', 'Author1']
And this is my code.
let obj = {};
try {
const json = document.querySelector('div.json');
if (json) {
let disc = JSON.parse(json.innerHTML);
let authors = disc.author;
if (typeof authors !== 'undefined' && Array.isArray(authors) && authors.length > 0) {
authors = authors.map((author) => {
if (typeof author === 'object' && author.name) {
return author.name;
} else {
return author;
}
});
}
if (typeof authors !== 'undefined' && !Array.isArray(authors) && typeof authors === 'object') {
authors = [authors.name];
}
if (typeof authors !== 'undefined' && typeof authors === 'string') {
authors = authors.split(',');
}
obj.cAu: authors.join(',');
}
} catch (e) { }
return obj;
My question is, is there a better way to do this in a more efficient way?