【问题标题】:Javascript - Convert large object literal into another object literalJavascript - 将大对象文字转换为另一个对象文字
【发布时间】:2013-02-24 16:08:00
【问题描述】:

我正在尝试将 Javascript 对象文字转换为另一个。我认为有一些循环是可能的,但我无法完成。目标结构如下所示,“convertedData”。

小提琴可以在这里找到: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 无法为我加载。另外,是的,你需要一个循环,可能是 3 个。
  • 大声笑,前段时间我有一个类似的面试问题。有固定的深度还是理论上是无限的?将需要几个循环或递归
  • 深度与示例中的一样,理论上不是无限的。
  • 即使我无法创建和保存 jsfiddle 来向您展示问题,它目前也无法加载。我不知道为什么。
  • 没有 JSON 对象这样的东西。只有 JSON 字符串。你所拥有的是一个 JavaScript 对象文字

标签: javascript jquery json object loops


【解决方案1】:

这是一个使用 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);
});

这是link to a jsbin fiddle

(在控制台中查看结果)

【讨论】:

    【解决方案2】:

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

    我已经完成了 2 遍,第 1 遍是构造一个简单的结果,它解析原始数据对象并创建以数字为键的字符串文字,第 2 遍是用相应的更新 convertedData var价值。

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

    【讨论】:

      【解决方案3】:

      使用 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

      【讨论】:

        【解决方案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);
        

        【讨论】:

        • 点赞。这朝着正确的方向发展,但它并不完全符合我的要求。
        • 我已经更新了小提琴 massley,请看一下!这是正确的方向!
        猜你喜欢
        • 2021-08-14
        • 2023-01-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-15
        • 2015-09-03
        • 2019-10-20
        • 1970-01-01
        相关资源
        最近更新 更多