I
I
Ilya2015-02-10 19:18:33
JavaScript
Ilya, 2015-02-10 19:18:33

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);

Current output:
[ { elem: 'item', content: 'About' },
  { elem: 'item', content: 'About' },
  { elem: 'item', content: 'About' } ]

You need to output:
[ { 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

1 answer(s)
Y
Yuri Shikanov, 2015-02-10
@AnImAsHkO

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 question

Ask a Question

731 491 924 answers to any question