简体   繁体   中英

Javascript - Convert large object literal into another object literal

I am trying to convert a Javascript object literal into another. I think it is possible with some loops, but i couldn't get it done. The target structure is shown below, "convertedData".

Fiddle can be found here: http://jsbin.com/ajemih/9/edit

Here's the JSON data:

var data =

{
"29-10-2012": {
    "1a": {
            "allMovement": "1",
            "allLoad": "2",
            "loadMovement": "3"
    },
        "1b": {
            "allMovement": 4,
            "allLoad": 5,
            "loadMovement": 6
    }
},
    "22-02-2013": {
    "1a": {
            "allMovement": "7",
            "allLoad": "8",
            "loadMovement": "9"
    },
        "1b": {
            "allMovement": "10",
            "allLoad": "11",
            "loadMovement": "12"
    }
}
};

for (day in data) {

    for (id in data[day]) {

        document.write(data[day][id].allMovement+"<br>");
        document.write(data[day][id].allLoad+"<br>");
        document.write(data[day][id].loadMovement+"<br>");

    }
}

/*

convertedData = [[1,7],
             [2, 8],
             [3, 9],
             ["4","10"],
             ["5","11"],
             ["6", "12"]];


convertedData = [["1a-allMovement-29-10-2012","1a-allMovement-22-02-2013],
                 ["1a-allLoad-29-10-2012", "1a-allLoad22-02-2013"],
                 ["1a-loadMovement-29-10-2012", "1a-loadMovement-22-02-2013"],
                 ["1b-allMovement-29-10-2012","1a-allMovement-22-02-2013"],
                 ["1b-allLoad-29-10-2012","1b-allLoad22-02-2013"],
                 ["1b-loadMovement-29-10-2012", "1b-loadMovement-22-02-2013"]];

*/

Try something like this, tweak it as you need:

var out = [],
    dateKey, idx, item, itemKey, inner;

for (dateKey in data) {
    if (data.hasOwnProperty(dateKey)) {
        idx = out.length;
        out[idx] = [];
        item = data[dateKey];
        for (itemKey in item) {
            if (item.hasOwnProperty(itemKey)) {
                inner = item[itemKey];
                out[idx].push(itemKey + '-' + inner.allMovement + '-' + inner.allLoad + '-' + inner.loadMovement);
            }
        } 
    }
}
console.log(out);

Here's a solution that uses the jQuery.each() function:

var convertedObj = {};
$.each(data, function(i0,val0) {
    $.each(val0, function(i1,val1) {
        $.each(val1, function(i2,val2) {
            if (!convertedObj[i1+"-"+i2]) convertedObj[i1+"-"+i2] = [];
            convertedObj[i1+"-"+i2].push(val2);            
        });
    });
});
var convertedData = [];
$.each(convertedObj, function(i,val) {
    convertedData.push(val);
});

Here's the link to a jsbin fiddle

(see the results in the console)

Using underscore.js:

var memo = {};

_.each(data, function (elem) { 
  _.each(elem, function (elem2, idx) {
    _.each (elem2, function(elem3, idx2) {
      if (typeof memo[idx + idx2] === 'undefined')
          memo[idx + idx2] = [];
      memo[idx + idx2].push(elem3);
    });
  });
});

memo = _.map(memo, function(e) { return e; });

// printing
document.write('[');
_.each(memo, function (e, idx) {
  document.write("[");
  _.each(e, function(ie, iidx) {
    if (typeof ie === 'string')
      document.write('"' + ie + '"');
    else
      document.write(ie);

    if (iidx != e.length - 1)
        document.write(",");
  });
  document.write("]");
  if (idx != memo.length - 1)
    document.write(",");
});
document.write(']');

Output is

[["1","7"],["2","8"],["3","9"],[4,"10"],[5,"11"],[6,"12"]]

jsbin link -> http://jsbin.com/ajemih/11

I think you got messed input data though as it doesn't comply with output according to types. Unless it is also part of this excercise... :-)

PS. as I understood you wanted literal that's why there's this whole section of document.write but you can ofc skip it if you don't want to print it

mz

DEMO: http://jsfiddle.net/XvwkX/1/

I have done it in 2 pass, 1st pass is to construct an easy result which parses the original data object and creates the string literal with the number as key and the 2nd pass is to update the convertedData var with the corresponding value.

var easyResult = {};
//first pass
$.each(data, function (d, o1) { //date, object1
    $.each (o1, function (t, o2) { //type, object2
        $.each(o2, function (s, n) { //string, ID
            easyResult[n] = t + '-' + s + '-' + d;
        });
    });
});

for (var i = 0; i < convertedData.length; i++ ) {
    for (var j = 0; j < convertedData[i].length; j++) {
        convertedData[i][j] = easyResult[""+convertedData[i][j]];
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM