Sign up ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I have a JavaScript array:

var data = [{abc: "vf",def: [{ a:"1", b:"3"},{a:"2",b:"4"}]}];

I want it to convert to:

[{"abc":"vf","a":"2","b":"4"},{"abc":"vf","a":"2","b":"4"}]

I have written the JavaScript code for it:

Javascript:

    var push_apply = Function.apply.bind([].push);
    var slice_call = Function.call.bind([].slice);

    Object.defineProperty(Array.prototype, "pushArrayMembers", {
        value: function() {
            for (var i = 0; i < arguments.length; i++) {
                var to_add = arguments[i];
                for (var n = 0; n < to_add.length; n+=300) {
                    push_apply(this, slice_call(to_add, n, n+300));
                }
            }
        }
    });

var globalResultArr = [];
var data = [{abc: "vf",def: [{ a:"1", b:"3"},{a:"2",b:"4"}]}];
function f(){
    for(var i=0;i<data.length;i++){    //Iterate Data Array
        var obj = data[i];
        var resultArray = [{}];
        for (var key in obj) {          // Iterate Object in Data Array
            if (obj.hasOwnProperty(key)) {
                if(Object.prototype.toString.call(obj[key]) === "[object Array]"){
                    var tempRes = $.extend(true, [], resultArray);
                    resultArray = [];
                    for(var k=0;k<tempRes.length;k++){
                        var tempResObj = tempRes[k];
                        for(var j=0;j<obj[key].length;j++){ // If it has array, then iterate it as well
                            var innerObj = obj[key][j]; //Iterate Object in inner array
                            for(var innerkey in innerObj){
                                if (innerObj.hasOwnProperty(innerkey)) {
                                    tempResObj[innerkey] = innerObj[innerkey];
                                }
                            }
                            resultArray.push(tempResObj);
                        }
                    }
                }else{
                    for(var i=0;i<resultArray.length;i++){
                        resultArray[i][key] = obj[key];
                    }
                }
            }
        }
        globalResultArr.pushArrayMembers(resultArray);
    }
    document.getElementById("test").innerHTML = JSON.stringify(globalResultArr);
}

f();

HTML:

<div id="test"></div>

How can I make this more space efficient? Is there any simpler approach?

JSFiddle : http://jsfiddle.net/La1687jc/

share|improve this question

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.