I have an issue to iterate through a pretty complex response I got from an API. To describe the whole situation.
I have an API which delivers XML. I am parsing XML to JavaScript objects using xml2js node module. Till some point it works fine, however I don't know how to iterate through the complex objects which I have parsed from xml.
Here is my JavaScript that is: getting the XML data from API > parsing XML to JS objects.
let headers = new Headers();
headers.append("Content-Type", "application/xml");
headers.append("Accept", "*/*");
headers.append("Access-Control-Allow-Origin", "http://localhost:8080");
headers.append("Access-Control-Allow-Credentials", "true");
headers.append("GET", "POST", "OPTIONS");
headers.append(
"Authorization",
"Basic [some_hash_here]"
);
const proxyurl = "https://cors-anywhere.herokuapp.com/";
const url =
"https://some-website-api.com/some/request"; // site that doesn’t send Access-Control-*
fetch(proxyurl + url, { headers: headers }) // https://cors-anywhere.herokuapp.com/https://some-website-api.com/some/request
.then(response => response.text())
.then(contents => {
console.log(contents);
var convert = require("xml-js");
var xml = contents;
var options = { ignoreComment: true, alwaysChildren: true, compact: true };
var result = convert.xml2js(xml, options); // converting xml to js objects
console.log(result);
alert(result.application.modules.module[0].moduleItem.dataField[0]._attributes.name);
});
The alert at the end works fine and I can get this particular value:
But how to iterate and get all other values from other moduleItem objects? So have the name also from:
application.modules.module[1].moduleItem.dataField[1]._attributes.name
application.modules.module[2].moduleItem.dataField[2]._attributes.name
application.modules.module[3].moduleItem.dataField[3]._attributes.name
etc...
To be able to render them on a list with Vue.js data models.
I tried below but with no luck.
let returnedName = result.application.modules.module.moduleItem.dataField._attributes.map(x => x.name);
this.nameModules = returnedName
Here is a structure of response I want to iterate in.