Javascript - 将大的对象字面量转换为另一个对象字面量

3
我希望您能够把一个JavaScript对象字面量转换成另一个对象。我认为可以通过一些循环实现,但我无法完成它。目标结构如下所示,“convertedData”。
您可以在这里找到Fiddle:http://jsbin.com/ajemih/9/edit 以下是JSON数据:
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"]];

*/

你的 jsFiddle 对我来说无法加载。另外,是的,你需要循环,可能需要三个。 - Halcyon
笑,我之前面试时有类似的问题。这个树有固定深度吗?还是理论上可以无限深?需要使用循环或递归几次才能完成? - jyore
深度就像示例中的一样,而不是理论上的无限。 - Michael Meier
没有所谓的 JSON 对象。只有 JSON 字符串。你所拥有的是 JavaScript 对象字面量。 - Alnitak
更新:为此问题设置赏金。 - Michael Meier
显示剩余3条评论
4个回答

4
尝试像这样做,根据需要进行调整:
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);

点赞。这是朝着正确的方向,但它并没有完全满足我的需求。 - Michael Meier
我已经大幅更新了这个代码片段,请看一下!这是正确的方向! - Michael Meier

2
这是一个使用 jQuery.each() 函数的解决方案:
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);
});

这是一个指向 jsbin fiddle 的链接
(在控制台中查看结果)

2
使用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(']');

输出结果为:

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

jsbin链接 -> http://jsbin.com/ajemih/11

我认为你的输入数据混乱,因为它与输出根据类型不符。除非这也是练习的一部分... :-)

附言:我理解你想要一个字面量,所以有了整个document.write部分,但如果你不想打印它,当然可以跳过它。

mz


2

示例: http://jsfiddle.net/XvwkX/1/

我将其分为两步,第一步是构建一个简单的结果,解析原始数据对象并创建带有数字键的字符串文字;第二步是使用相应的值更新convertedData变量。

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]];
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接