JSON Bind to Javascript Object - javascript

All,I saw lot of examples talking about how to parse json to js object(or convert json to js object) in SO. But I didn't saw an example which is binding json to already defined js object. Now I have some trouble with it when I am trying to make it.Please help me to review it . thanks.
What I had done so far looks like below:
top=function()
{
this.encoding ='';
this.nodes=[];
this.lastid='';
//I don't how to defined the attributes key in json which is a object.
//I think there should exist a parse and toJson function;
//this.parse= function(jsonstring){...};
//this.toJson=function(){var jsonstr=....;return jsonstr;};
};
group=functon()
{
this.id='';
this.type='';
this.subnodes=[];
this.tagname='';
//....
}
top is the root which contains uncertain numbers of block which is self-included object .
and the Json is generate by Jackson, which looks like below .
{
"nodes": [
{
"type": "group",
"id": 11,
"tagName": "blockrow",
"prefix": "aa",
"cutomTag": null,
"attributes": {
"width": "12"
//...more
},
"subNodes": [
{
"type": "group",
"id": 111,
"tagName": "blockcol",
"prefix": "aa",
"cutomTag": null,
"attributes": {
"width": "4"
},
"subNodes": [
{
"type": "group",
"id": 1111,
"tagName": "section",
"prefix": "aa",
"cutomTag": null,
"attributes": {
"title": "NewSection",
"width": "12"
},
"subNodes": [
{
"type": "leaf",
"id": 11111,
"tagName": "message",
"prefix": "aa",
"cutomTag": null,
"attributes": {
"key": "aa_login_success"
}
}
]
}
]
},
{
"type": "group",
"id": 112,
"tagName": "blockcol",
"prefix": "aa",
"cutomTag": null,
"attributes": {
"width": "4"
},
"subNodes": [
{
"type": "group",
"id": 1121,
"tagName": "section",
"prefix": "aa",
"cutomTag": null,
"attributes": {
"title": "NewSection",
"width": "12"
},
"subNodes": [
{
"type": "leaf",
"id": 11211,
"tagName": "message",
"prefix": "aa",
"cutomTag": {
"type": "cutomTag",
"beginPos": 20,
"endPos": 50,
"id": -1
},
"attributes": {
"key": "aa_login_failed"
}
}
]
}
]
},
{
"type": "group",
"id": 113,
"tagName": "blockcol",
"prefix": "aa",
"cutomTag": null,
"attributes": {
"width": "4"
},
"subNodes": null
}
]
},
{
"type": "group",
"id": 12,
"tagName": "blockrow",
"prefix": "aa",
"cutomTag": null,
"attributes": {
"width": "12"
},
"subNodes": [
{
"type": "group",
"id": 121,
"tagName": "blockcol",
"prefix": "aa",
"cutomTag": null,
"attributes": {
"width": "6"
},
"subNodes": null
},
{
"type": "group",
"id": 122,
"tagName": "blockcol",
"prefix": "aa",
"cutomTag": null,
"attributes": {
"width": "6"
},
"subNodes": null
}
]
}
],
"version": 1,
"encoding": "unicode",
"lastId": 1
}
the kind of code I imagine would looks like below :
var curTop= new top();
curTop.parse(jsonstring);
//manipulate the curTop object...
//...
var jsonStr=curTop.toJson();
//convert object to json.
I hope my direction so far to solve the problem is right, if it is not right, I hope you give me some kind comments.

You should define functions on the prototype:
top.prototype.parse= function(jsonstring){...};
This way they are shared between instances. You can access members of the current instance via this.variable syntax.
For more information on how prototype works you can check out : https://stackoverflow.com/a/4778408/390330
Your complete function will look something like:
top.prototype.parse= function(jsonstring){
var data = JSON.parse( json_string );
this.encoding = data.encoding;
// etc.
};

try this one ..this one way to convert string to object..
var response = eval('(' + data + ')');

try this code..
var arr_from_json = JSON.parse( json_string );

Related

Loop through a JSON object and display items as unordered list

i have a fetch that return a json object like this:
{
"id": "xxxxxxxxxxxxxxxxxxx2",
"name": "name",
"instant_invite": "link",
"channels": [
{
"id": "xxxxxxxxxxxxxxxxxxx2",
"name": "Altri Giochi",
"position": 8
},
{
"id": "xxxxxxxxxxxxxxxxxxx2",
"name": "Ascolto Musica",
"position": 11
},
],
"members": [
{
"id": "0",
"username": "xxxxxxxxxxxxxx",
"discriminator": "0000",
"avatar": null,
"status": "idle",
"avatar_url": "https://url"
},
],
"presence_count": 3
}
now i'm trying to map and display all these items to make an unordered list for my website, but i can't map this object with this.myResponse.map...i get an error "map is not a function".
i'm definitely lost here and i need some help to make an unordered list that contain all members name, avatar and other stuff.
can someone help me on this in vanilla js?
You can loop through the object using Object.keys(). Here's an example
let data = {
"id": "xxxxxxxxxxxxxxxxxxx2",
"name": "name",
"instant_invite": "link",
"channels": [{
"id": "xxxxxxxxxxxxxxxxxxx2",
"name": "Altri Giochi",
"position": 8
},
{
"id": "xxxxxxxxxxxxxxxxxxx2",
"name": "Ascolto Musica",
"position": 11
},
],
"members": [{
"id": "0",
"username": "xxxxxxxxxxxxxx",
"discriminator": "0000",
"avatar": null,
"status": "idle",
"avatar_url": "https://url"
},
{
"id": "1",
"username": "yyyyyyyyyyyyy",
"discriminator": "0000",
"avatar": null,
"status": "idle",
"avatar_url": "https://url"
},],
"presence_count": 3
}
data.members.forEach(m => {
// start the UL
let ul = "<ul class='member'>";
// loop through using Object.keys(m) or preset array of keys
['username','avatar'].forEach(md => {
ul += `<li>${md}: ${m[md]}</li>`;
})
ul += "</ul>";
document.querySelector('#members').innerHTML += ul;
})
<div id='members'></div>

Javascript Recursive function to build Tree

Hi I am using JavaScript and jQuery as client side script. I am little bit new to Recursive functions. I have a JSON data as below and I have tried to make a tree structure using below JSON data by writing a recursive function but I am not able to build the tree structure.
var jsonData = { "$id": "45", "_children": [{ "$id": "46", "_children": [{ "$id": "47", "_children": [{ "$id": "48", "_children": [{ "$id": "49", "_children": null, "id": "Test1", "text": "Text1", "name": "name1", "parent": null, "root": { "$ref": "49" }, "depth": 0, "children": [] }], "id": "id1", "text": "text2", "name": "name2", "parent": null, "root": { "$ref": "48" }, "depth": 0, "children": [{ "$ref": "49" }] }], "id": "id3", "text": "text4", "name": "name4", "parent": null, "root": { "$ref": "47" }, "depth": 0, "children": [{ "$ref": "48" }] }, { "$id": "50", "_children": [{ "$id": "51", "_children": [{ "$id": "52", "_children": null, "id": "id6", "text": "text6", "name": "name6", "parent": null, "root": { "$ref": "52" }, "depth": 0, "children": [] }], "id": "id7", "text": "text7", "name": "name7", "parent": null, "root": { "$ref": "51" }, "depth": 0, "children": [{ "$ref": "52" }] }], "id": "id8", "text": "text8", "name": "name8", "parent": null, "root": { "$ref": "50" }, "depth": 0, "children": [{ "$ref": "51" }] }], "id": "id9", "text": "text9", "name": "name9", "parent": null, "root": { "$ref": "46" }, "depth": 0, "children": [{ "$ref": "47" }, { "$ref": "50" }] }, { "$id": "53", "_children": [{ "$id": "54", "_children": null, "id": "id10", "text": "text10", "name": "name10", "parent": null, "root": { "$ref": "54" }, "depth": 0, "children": [] }], "id": "id11", "text": "text11", "name": "name11", "parent": null, "root": { "$ref": "53" }, "depth": 0, "children": [{ "$ref": "54" }] }], "id": "0", "text": "0", "name": "", "parent": null, "root": { "$ref": "45" }, "depth": 0, "children": [{ "$ref": "46" }, { "$ref": "53" }] }
Required Output:
var treeNode = {
id: 101, // random
text: object.name,
icon: "fas fa-plus",
subNode: {
// id, text, icon and subNode of Children object
// recursive data, So on....
}
};
Can anyone suggest me or help me to write javascript or jQuery Recursive function based on above JSON data so I can build tree structure. I know I am asking about help because I do have less knowledge about recursive function.
If we abstract this a bit, it's pretty easy to write a general-purpose tree-mapping function. Then we can supply two callback functions: one to find the child nodes of the input and one to build the output node based on the input and the mapped children. Such a function turns out to be surprisingly simple:
const mapTree = (getChildren, transformNode) => (tree) =>
transformNode (
tree,
(getChildren (tree) || []) .map (mapTree (getChildren, transformNode))
)
For your data, getChildren is simply (node) => node._children
And the node transformation might be as simple as:
const transformNode = (node, children) =>
({
id: node.$id, // or a randomizing call?
text: node.name,
icon: "fas fa-plus", // is this really a fixed value?
subNode: children
})
Putting this together we get
const mapTree = (getChildren, transformNode) => (tree) =>
transformNode (
tree,
(getChildren (tree) || []) .map (mapTree (getChildren, transformNode))
)
const kids = (node) => node._children
const transformNode = (node, children) =>
({
id: node.$id,
text: node.name,
icon: "fas fa-plus",
subNode: children
})
const myTransform = mapTree (kids, transformNode)
const jsonData = { "$id": "45", "_children": [{ "$id": "46", "_children": [{ "$id": "47", "_children": [{ "$id": "48", "_children": [{ "$id": "49", "_children": null, "id": "Test1", "text": "Text1", "name": "name1", "parent": null, "root": { "$ref": "49" }, "depth": 0, "children": [] }], "id": "id1", "text": "text2", "name": "name2", "parent": null, "root": { "$ref": "48" }, "depth": 0, "children": [{ "$ref": "49" }] }], "id": "id3", "text": "text4", "name": "name4", "parent": null, "root": { "$ref": "47" }, "depth": 0, "children": [{ "$ref": "48" }] }, { "$id": "50", "_children": [{ "$id": "51", "_children": [{ "$id": "52", "_children": null, "id": "id6", "text": "text6", "name": "name6", "parent": null, "root": { "$ref": "52" }, "depth": 0, "children": [] }], "id": "id7", "text": "text7", "name": "name7", "parent": null, "root": { "$ref": "51" }, "depth": 0, "children": [{ "$ref": "52" }] }], "id": "id8", "text": "text8", "name": "name8", "parent": null, "root": { "$ref": "50" }, "depth": 0, "children": [{ "$ref": "51" }] }], "id": "id9", "text": "text9", "name": "name9", "parent": null, "root": { "$ref": "46" }, "depth": 0, "children": [{ "$ref": "47" }, { "$ref": "50" }] }, { "$id": "53", "_children": [{ "$id": "54", "_children": null, "id": "id10", "text": "text10", "name": "name10", "parent": null, "root": { "$ref": "54" }, "depth": 0, "children": [] }], "id": "id11", "text": "text11", "name": "name11", "parent": null, "root": { "$ref": "53" }, "depth": 0, "children": [{ "$ref": "54" }] }], "id": "0", "text": "0", "name": "", "parent": null, "root": { "$ref": "45" }, "depth": 0, "children": [{ "$ref": "46" }, { "$ref": "53" }] }
console .log (myTransform (jsonData))
This does something slightly different from your requested output. You had written subNode: { ... }, but instead I'm returning an array of objects, subNodes: [ ... ], as I don't make any real sense of a plain object here.
Also, this will yield an empty subNodes array if an input node has no children. If you would rather not have the subNodes property, you could replace
subNode: children
with something like
...(children .length ? {subNode: children} : {})
Obviously, you don't need the named helpers and could call mapTree with anonymous functions like this:
const myTransform = mapTree (
(node) => node._children,
(node, children) =>
({
id: node.$id,
text: node.name,
icon: "fas fa-plus",
subNode: children
})
)
This mapTree function was very easy to write, as I didn't have to think about any details of the output or input formats as I wrote it. But perhaps that abstraction is not helpful to me, and I'm never going to use it except here. If so, I can simply rework the abstract version by plugging the hard-coded callbacks directly. With only a little manipulation, that will turn it into this version:
const newTransform = (node) =>
({
id: node.$id,
text: node.name,
icon: "fas fa-plus",
subNode: (node._children || []).map(newTransform)
})
const jsonData = { "$id": "45", "_children": [{ "$id": "46", "_children": [{ "$id": "47", "_children": [{ "$id": "48", "_children": [{ "$id": "49", "_children": null, "id": "Test1", "text": "Text1", "name": "name1", "parent": null, "root": { "$ref": "49" }, "depth": 0, "children": [] }], "id": "id1", "text": "text2", "name": "name2", "parent": null, "root": { "$ref": "48" }, "depth": 0, "children": [{ "$ref": "49" }] }], "id": "id3", "text": "text4", "name": "name4", "parent": null, "root": { "$ref": "47" }, "depth": 0, "children": [{ "$ref": "48" }] }, { "$id": "50", "_children": [{ "$id": "51", "_children": [{ "$id": "52", "_children": null, "id": "id6", "text": "text6", "name": "name6", "parent": null, "root": { "$ref": "52" }, "depth": 0, "children": [] }], "id": "id7", "text": "text7", "name": "name7", "parent": null, "root": { "$ref": "51" }, "depth": 0, "children": [{ "$ref": "52" }] }], "id": "id8", "text": "text8", "name": "name8", "parent": null, "root": { "$ref": "50" }, "depth": 0, "children": [{ "$ref": "51" }] }], "id": "id9", "text": "text9", "name": "name9", "parent": null, "root": { "$ref": "46" }, "depth": 0, "children": [{ "$ref": "47" }, { "$ref": "50" }] }, { "$id": "53", "_children": [{ "$id": "54", "_children": null, "id": "id10", "text": "text10", "name": "name10", "parent": null, "root": { "$ref": "54" }, "depth": 0, "children": [] }], "id": "id11", "text": "text11", "name": "name11", "parent": null, "root": { "$ref": "53" }, "depth": 0, "children": [{ "$ref": "54" }] }], "id": "0", "text": "0", "name": "", "parent": null, "root": { "$ref": "45" }, "depth": 0, "children": [{ "$ref": "46" }, { "$ref": "53" }] }
console .log (newTransform (jsonData))
There's an important point here. This generic function was much easier to write than if I'd tried to write something to convert your format directly. While there is a danger in too-early abstraction, it also can offer significant benefits. I might well choose to keep only that last version, but the generic abstraction simplified the development of it.
It can be something like that, with using the json data model
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="lib/style.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<div id="myDiv"></div>
</body>
<script>
var treeData={
"Id":"10",
"text":"Document Categories",
"icon":"fas fa-plus",
"subNode":
[
{
"Id":"11",
"text":"Pdf Documents",
"icon":"fas fa-plus",
"subNode":[
{
"Id":"31",
"text":"Book Pdfs",
"icon":"fas fa-plus",
"subNode":[]
},
{
"Id":"32",
"text":"EPub",
"icon":"fas fa-plus",
"subNode":[
{
"Id":"20",
"text":"EBook Epubs1",
"icon":"fas fa-plus",
"subNode":[]
},
{
"Id":"30",
"text":"EBook Epubs2",
"icon":"fas fa-plus",
"subNode":[]
}
]
}
]
},
{
"Id":"33",
"text":"Text Documents",
"icon":"fas fa-plus",
"subNode":[
{
"Id":"32",
"text":"Book Text",
"icon":"fas fa-plus",
"subNode":[]
},
{
"Id":"35",
"text":"Automatic Text",
"icon":"fas fa-plus",
"subNode":[]
}
]
}
]
};
var newTree = AddRecursive(null, treeData);
var treeDiv = $('#myDiv');
treeDiv.append(newTree);
function AddRecursive(tree, data) {
if (tree == null) {
tree = $('<ul/>');
tree.attr('id', 'treeID');
}
var listU = $('<ul />');
listU.addClass('ul class');
var listItem = $('<li />');
listItem.addClass('li class');
listItem.attr('data-id', data.Id);
var link = $('<a />');
var i = $('<i/>').addClass('fa fa-folder');
link.append(i);
//link.addClass("linkClass");
link.append(data.text);
listItem.append(link);
if (data.subNode.length > 0) {
var span = $(' <span />');
span.addClass('fa-chevron-down');
link.append(span);
}
listU.append(listItem);
tree.append(listU);
for (i in data.subNode) {
AddRecursive(listItem, data.subNode[i]);
}
return tree;
}
</script>
</html>

Paasing an object into an array of arrays

Have an object that needs to be pass inside the array of source using javascript,throwing an error spec is undefined when using push function. will push function work for this scenario
var a = [
"name": "ben",
"type": "male",
"appType": "human",
"spec": {
"view": "instanceview",
"sink": {
"source": [{
"data": {
"path": "google/path",
"name": "test",
"Id": "11234",
},
"ref": "www.xyz.com",
"id": "isdfjsbfjsfb",
"resourceType": "app"
}
],
},
},
}]
var b = {
"data": {
"path": "google/path",
"name": "goldengate",
"Id": "11234vndslknvlsmnv",
},
"ref": "www.xyz.com",
"id": "6452367e5375",
"resourceType": "app"
}
a.spec.sink.source.push(b);
would expect b to be pushed to source
An array with string keys is not a valid structure, you need to convert a to an object
var a = { // <-- here
"name": "ben",
"type": "male",
"appType": "human",
"spec": {
"view": "instanceview",
"sink": {
"source": [
{
"data": {
"path": "google/path",
"name": "test",
"Id": "11234",
},
"ref": "www.xyz.com",
"id": "isdfjsbfjsfb",
"resourceType": "app"
}
],
},
},
} // <-- here

How to correctly use JSON.parse()? JSON result is not valid

When I use JSON.parse(myJSONString) the result is not a valid JSON file. I'm in an nodejs environment. Any Ideas what I can fix in my code? I user XML2JS to converte an XML Api call to JS.
I have printed out the results and already dived deeper into JSON.parse but didn't find further information...
exports.getStations = functions.https.onCall(async (data) => {
let stations
await axios.get(encodeURI(`XMLAPi`))
.then(async (response) => {
parseString(response.data, (err, result) => {
stations = JSON.stringify(result)
console.log(stations) //First console.log
})
})
.catch((error) => {
console.log(error)
})
console.log(JSON.parse(stations)) //Second console.log
return JSON.parse(stations)
})
Result for first console.log (valid JSON but String):
{"itdRequest":{"$":{"xsi:noNamespaceSchemaLocation":"itd.xsd","language":"DE","sessionID":"EfaOpenServiceT_2882840828","client":"axios/0.19.0","serverID":"EfaOpenServiceT_","clientIP":"127.0.0.1","version":"10.3.5.46","virtDir":"static02","xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance"},"itdStopFinderRequest":{"$":{"requestID":"1"},"itdOdv":{"$":{"type":"any","usage":"sf","anyObjFilter":"42"},"itdOdvPlace":{"$":{"state":"empty"},"odvPlaceElem":""},"itdOdvName":{"$":{"state":"list"},"itdMessage":{"$":{"type":"error","module":"BROKER","code":"-8011"}},"odvNameElem":[{"_":"Mettmann, Stadtwald S","$":{"value":"0:1","selected":"1","listIndex":"0","streetName":"","omc":"5158024","placeID":"5","x":"6987248.99348","y":"51250980.94198","mapName":"WGS84","id":"20019083","anyType":"stop","anyTypeSort":"2","nameKey":"","locality":"Mettmann","postCode":"","objectName":"Stadtwald S","buildingName":"","buildingNumber":"","matchQuality":"235","stateless":"20019083"}},{"_":"Mettmann, ME-Zentrum S","$":{"value":"1:2","selected":"0","listIndex":"1","streetName":"","omc":"5158024","placeID":"5","x":"6979002.45917","y":"51249372.83702","mapName":"WGS84","id":"20019020","anyType":"stop","anyTypeSort":"2","nameKey":"","locality":"Mettmann","postCode":"","objectName":"ME-Zentrum S","buildingName":"","buildingNumber":"","matchQuality":"234","stateless":"20019020"}},{"_":"Mettmann, Neanderthal S","$":{"value":"2:3","selected":"0","listIndex":"2","streetName":"","omc":"5158024","placeID":"5","x":"6953346.57466","y":"51227837.93128","mapName":"WGS84","id":"20019191","anyType":"stop","anyTypeSort":"2","nameKey":"","locality":"Mettmann","postCode":"","objectName":"Neanderthal S","buildingName":"","buildingNumber":"","matchQuality":"234","stateless":"20019191"}}],"odvNameInput":"mettmann"},"genAttrList":{"genAttrElem":[{"name":"anyObjFilter","value":"STOP"},{"name":"anyObjFilter","value":"ADDRESS"},{"name":"anyObjFilter","value":"POI"}]}},"itdDateTime":{"$":{"ttpFrom":"20190601","ttpTo":"20191231"},"itdDate":{"$":{"day":"10","month":"8","year":"2019","weekday":"7"}},"itdTime":{"$":{"hour":"16","minute":"4"}}}}}}
Result for second console.log (invalid JSON after parse):
Object {
"data": Object {
"itdRequest": Object {
"$": Object {
"client": "axios/0.19.0",
"clientIP": "127.0.0.1",
"language": "DE",
"serverID": "EfaOpenServiceT_",
"sessionID": "EfaOpenServiceT_2882840828",
"version": "10.3.5.46",
"virtDir": "static02",
"xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
"xsi:noNamespaceSchemaLocation": "itd.xsd",
},
"itdStopFinderRequest": Object {
"$": Object {
"requestID": "1",
},
"itdDateTime": Object {
"$": Object {
"ttpFrom": "20190601",
"ttpTo": "20191231",
},
"itdDate": Object {
"$": Object {
"day": "10",
"month": "8",
"weekday": "7",
"year": "2019",
},
},
"itdTime": Object {
"$": Object {
"hour": "16",
"minute": "4",
},
},
},
"itdOdv": Object {
"$": Object {
"anyObjFilter": "42",
"type": "any",
"usage": "sf",
},
"genAttrList": Object {
"genAttrElem": Array [
Object {
"name": "anyObjFilter",
"value": "STOP",
},
Object {
"name": "anyObjFilter",
"value": "ADDRESS",
},
Object {
"name": "anyObjFilter",
"value": "POI",
},
],
},
"itdOdvName": Object {
"$": Object {
"state": "list",
},
"itdMessage": Object {
"$": Object {
"code": "-8011",
"module": "BROKER",
"type": "error",
},
},
"odvNameElem": Array [
Object {
"$": Object {
"anyType": "stop",
"anyTypeSort": "2",
"buildingName": "",
"buildingNumber": "",
"id": "20019083",
"listIndex": "0",
"locality": "Mettmann",
"mapName": "WGS84",
"matchQuality": "235",
"nameKey": "",
"objectName": "Stadtwald S",
"omc": "5158024",
"placeID": "5",
"postCode": "",
"selected": "1",
"stateless": "20019083",
"streetName": "",
"value": "0:1",
"x": "6987248.99348",
"y": "51250980.94198",
},
"_": "Mettmann, Stadtwald S",
},
Object {
"$": Object {
"anyType": "stop",
"anyTypeSort": "2",
"buildingName": "",
"buildingNumber": "",
"id": "20019020",
"listIndex": "1",
"locality": "Mettmann",
"mapName": "WGS84",
"matchQuality": "234",
"nameKey": "",
"objectName": "ME-Zentrum S",
"omc": "5158024",
"placeID": "5",
"postCode": "",
"selected": "0",
"stateless": "20019020",
"streetName": "",
"value": "1:2",
"x": "6979002.45917",
"y": "51249372.83702",
},
"_": "Mettmann, ME-Zentrum S",
},
Object {
"$": Object {
"anyType": "stop",
"anyTypeSort": "2",
"buildingName": "",
"buildingNumber": "",
"id": "20019191",
"listIndex": "2",
"locality": "Mettmann",
"mapName": "WGS84",
"matchQuality": "234",
"nameKey": "",
"objectName": "Neanderthal S",
"omc": "5158024",
"placeID": "5",
"postCode": "",
"selected": "0",
"stateless": "20019191",
"streetName": "",
"value": "2:3",
"x": "6953346.57466",
"y": "51227837.93128",
},
"_": "Mettmann, Neanderthal S",
},
],
"odvNameInput": "mettmann",
},
"itdOdvPlace": Object {
"$": Object {
"state": "empty",
},
"odvPlaceElem": "",
},
},
},
},
},
}
You are already converting to string as a parsestring function. But it's also converting to JSON.stringify().
You can try check this value
let stations = await axios.get(encodeURI(`XMLAPi`));
console.log(JSON.stringify(stations.data)) // What is value??

Check if the nested object contains a specific key, then replace a key of the parent object

I've a nested object.
Now, I need to check if the object contains 'items' as a key anywhere which is an 'array' always, then replace 'type' : 'list' by 'type': 'array' of the parent.
It works well for the 1st level but when it comes to the nested object which contains 'items' again, I'm stuck.
function convertData() {
const arr = {
"type": "list",
"items": [{
"type": "list",
"items": [{
"type": "string",
"value": 0,
"unit": "",
"pattern": "^(auto|0)$|^[+-]?[0-9]+(\\.)?([0-9]+)?(rem|px|em|ex|%|in|cm|mm|pt|pc)$"
}, {
"type": "string",
"value": 0.1875,
"unit": "rem",
"pattern": "^(auto|0)$|^[+-]?[0-9]+(\\.)?([0-9]+)?(rem|px|em|ex|%|in|cm|mm|pt|pc)$"
}, {
"type": "string",
"value": 0.75,
"unit": "rem",
"pattern": "^(auto|0)$|^[+-]?[0-9]+(\\.)?([0-9]+)?(rem|px|em|ex|%|in|cm|mm|pt|pc)$"
}, {
"type": "string",
"value": 0,
"unit": "",
"pattern": "^(auto|0)$|^[+-]?[0-9]+(\\.)?([0-9]+)?(rem|px|em|ex|%|in|cm|mm|pt|pc)$"
}]
}, {
"type": "string",
"value": {
"r": 161,
"g": 161,
"b": 161,
"a": 0.75,
"hex": "#a1a1a1"
},
"pattern": "^rgba?\\(((25[0-5]|2[0-4]\\d|1\\d{1,2}|\\d\\d?)\\s*,\\s*?){2}(25[0-5]|2[0-4]\\d|1\\d{1,2}|\\d\\d?)\\s*,?\\s*([01]\\.?\\d*?)?\\)"
}]
};
if (Array.isArray(arr.items)) {
arr.type = "array";
console.log(arr);
}
}
<button onclick="convertData()">Click me!</button>
You can do that using recursion.
Create a function changeValue which takes an object as argument.
Check the object has key items using Object.hasOwnProperty()
If it contains change the type to "array" and call the function recursively on its each item.
function convertData() {
const arr = { "type": "list", "items": [{ "type": "list", "items": [{ "type": "string", "value": 0, "unit": "", "pattern": "^(auto|0)$|^[+-]?[0-9]+(\\.)?([0-9]+)?(rem|px|em|ex|%|in|cm|mm|pt|pc)$" }, { "type": "string", "value": 0.1875, "unit": "rem", "pattern": "^(auto|0)$|^[+-]?[0-9]+(\\.)?([0-9]+)?(rem|px|em|ex|%|in|cm|mm|pt|pc)$" }, { "type": "string", "value": 0.75, "unit": "rem", "pattern": "^(auto|0)$|^[+-]?[0-9]+(\\.)?([0-9]+)?(rem|px|em|ex|%|in|cm|mm|pt|pc)$" }, { "type": "string", "value": 0, "unit": "", "pattern": "^(auto|0)$|^[+-]?[0-9]+(\\.)?([0-9]+)?(rem|px|em|ex|%|in|cm|mm|pt|pc)$" }] }, { "type": "string", "value": { "r": 161, "g": 161, "b": 161, "a": 0.75, "hex": "#a1a1a1" }, "pattern": "^rgba?\\(((25[0-5]|2[0-4]\\d|1\\d{1,2}|\\d\\d?)\\s*,\\s*?){2}(25[0-5]|2[0-4]\\d|1\\d{1,2}|\\d\\d?)\\s*,?\\s*([01]\\.?\\d*?)?\\)" }] };
changeValue(arr);
console.log(arr)
}
function changeValue(obj){
if(obj.hasOwnProperty('items')){
obj.type = "array";
obj.items.forEach(x => changeValue(x))
}
}
<button onclick="convertData()">Click me!</button>

Categories