Answer the question
In order to leave comments, you need to log in
How to do correct output in nested loops?
var data = {
content: [{
api: 'menu',
content: {
elem: 'item'
}
}]
};
var apiData = {
menu: ['Home', 'Content', 'About']
};
test = function (json, api) {
if(Array.isArray(json)) {
json.forEach(function (element) {
if(typeof element.content === 'object') {
var content = [];
api[element.api].forEach(function (apiElement, n) {
content[n] = element.content;
content[n].content = apiElement;
});
console.log(content);
}
if (typeof element.content !== 'string') {
test(element.content, api);
} else {
test(element, api);
}
});
} else {
if(typeof json !== 'string') {
test(json.content, api);
}
}
};
test(data, apiData);
[ { elem: 'item', content: 'About' },
{ elem: 'item', content: 'About' },
{ elem: 'item', content: 'About' } ]
[ { elem: 'item', content: 'Home' },
{ elem: 'item', content: 'Content' },
{ elem: 'item', content: 'About' } ]
Answer the question
In order to leave comments, you need to log in
content[n] = element.content
here you are assigning a value by reference. Because of this, such a result.
You need something like this:
api[element.api].forEach(function (apiElement, n) {
content[n] = {};
for (var i in element.content) {
content[n][i] = element.content[i];
}
content[n].content = apiElement;
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question