javascript如何使对象内联

时间:2013-12-10 09:40:08

标签: javascript matrix

我有一些不同嵌套的对象。例如:
Object1

{
    data: {somePage1.php:
                         {0: 
                             {function:'getPrice',
                             item:'0568000085',
                             line: 6},
                          1:
                             {function:'getCurrency',
                             item:'066000089'
                             line: 9}
                          },
           somePage2.php:...
      }
}

Object2的

data: {EUR:{currency:45.0417}USD:{currency:33.0346}}

等等。我需要的是函数,它将使任何对象内联

希望的结果是:

Object1

{row1:{key1:somePage1.php, key2:0, function:'getPrice', item:'0568000085', line:6}
 row2:{key1:somePage1.php, key2:1, function:'getCurrency', item:'066000089', line:9}
 row3:{key1:somePage2.php, key2:0, function: ...                                   }
 row4:...
}

Object2的

{
 row1:{key1:EUR, currency:45.0417}
 row2:{key1:USD, currency:33.0346}
}

很明显我需要递归,但我无法弄清楚整个函数,如下所示:

    this.row = 0;
this.inline = function(d){
var that = this;
var data = d||that.data;//data have been append to this object onload
    $.each(data, function(attr, value){
        $.each(data[attr], function(att, val){
            if(typeof(val) === 'object' || typeof(val) === 'array'){
                that.inline(data[attr][att]);
            }else{
                $.each(data, function(){
                    that.row++;
                });
                console.log(value);
            }
        }); 
    });
console.log('======> '+that.row);
},

2 个答案:

答案 0 :(得分:0)

这将获取对象数据的每个(本地)属性,将其作为rowN属性放在行中,并将旧属性名称作为键属性,我不建议像在一个示例中那样递增键属性。

var i = 0, rows = {}, data = {a: {t: 1}, b: {g: 2}, c: { z: 3}}; 
$.each(data, 
     function (prop, obj) { 
          rows['row' + i++] = $.extend({ key: prop}, obj); 
     }
);

BTW - 双嵌套循环不是递归。还不清楚你需要递归,许多解决方案都可以通过循环和递归执行来解决。上面的例子不使用递归,而是使用命令循环。

http://en.wikipedia.org/wiki/Recursion_(computer_science)

答案 1 :(得分:0)

function convert(d) {
  var r = {}, j = 0;
  for (var i in d) {
    r['row'+(j++)] = flatten({key1:i}, d[i], 2);
  }
  return r;
}
function flatten(r, d, l) {
  for (var i in d) {
    var c = d[i];
    if (c && typeof c == 'object') {
      r['key'+l] = i;
      flatten(r, c, l+1);
    } else {
      r[i] = c;
    }
  }
  return r;
}

这使用递归并假设json是任意嵌套的,并将key1,key2等分配给那些值为非null对象的键。

编辑:修复以使第一个键使用rowX(对所有单个字母var名称抱歉)