0

I have an array multidimensional that contains two nested arrays.

Looks like this:

$scope.multidimensionalArray = [{
            id:1,
            name:"John",
            ....
            nestedArray1:[{
                importantKey1:"important_data1",
                ....
                    nestedArray2:[{
                            importantKey2:"important_data2",
                                ....
                            }
                                 ]},
                                 ....
                                         ]}];

How can transform this multidimensional array in one dimensional that have to look like this:

$scope.oneDimensional = [
    { 
        id:1,
        name:"John",
        importantKey1:"important_data1", 
        importantKey2: "important_data2",
        ....
    },
    ....
   ];

2 Answers 2

3

This solution features Object.keys() and Array.prototype.forEach().

function getProperties(o, obj) {
    Object.keys(o).forEach(function (k) {
        if (Array.isArray(o[k])) {
            getItems(o[k], obj);
        } else {
            obj[k] = o[k];
        }
    });
}        

function getItems(array, obj) {
    array.forEach(function (o) {
        getProperties(o, obj);
    });
}

var multidimensionalArray = [{ id: 1, name: "John", nestedArray1: [{ importantKey1: "important_data1", nestedArray2: [{ importantKey2: "important_data2", }] }] }, { id: 2, name: "Johanna", nestedArray1: [{ importantKey1: "important_data11", nestedArray2: [{ importantKey2: "important_data12", }] }] }],
    result = multidimensionalArray.map(function (o) {
        var obj = {};
        getProperties(o, obj);
        return obj;
    });

    document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your answer but unfortunately result is the same. I get the same multidimensional array.
Nevermind i have copied your answer wrong. It works! Thank You very much.
0

Like in sql or generally relational databases, the only chance to have this data in ode dimension is that you multiple times use these things that are one: so it would be id, name multiple times and for each this you should have one entry from your nested array.

If there is double-level nesting, then you probably have to repeat more fields. Look for JOIN definition from sql, it may flesh something about this.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.