如何在没有硬编码名称的情况下转换这个json结构?

时间:2015-10-28 05:30:53

标签: javascript json

我有这个json变量。

var x =
    [
        {
            x1_year: 0.73,
            x2_year: 0.84,
            x5_year: 1.37,
            x10_year: 1.88                
        }
    ];

我想将其转换为这样;

var y =
    [
        {
            c: [{
                v: "x1_year"
            },
                {
                    v: "0.73"
                }]
        },
        {
            c: [{
                v: "x2_year"
            },
                {
                    v: "0.84"
                }]
        },
        {
            c: [{
                v: "x5_year"
            },
                {
                    v: "1.37"
                }]
        },
        {
            c: [{
                v: "x10_year"
            },
                {
                    v: "1.88"
                }]
        }
    ];

我有一个使y1 === y的解决方案。它看起来像这样;

var y1 = [
    {
        c:
        [
            {"v": "x1_year"},
            {"v": x[0].x1_year}
        ]
    },
    {
        c:
            [
                {"v": "x2_year"},
                {"v": x[0].x2_year}
            ]
    },
    {
        c:
            [
                {"v": "x5_year"},
                {"v": x[0].x5_year}
            ]
    },
    {
        c:
            [
                {"v": "x10_year"},
                {"v": x[0].x10_year}
            ]
    }
];

不幸的是,这是一个糟糕的解决方案。问题是我的解决方案硬编码了密钥的名称,例如x1_yearx1_yearx5_yearx10_year

我希望有一个改进的解决方案,使得密钥的名称不是硬编码的。更好的是,x中可以有任意数量的键名对。如果可能的话,如何做到这一点?

2 个答案:

答案 0 :(得分:2)

试试这个

var temp = [];
x.forEach(function(y) {

    for (var i in y) {
        var temp1 = []
        temp1.push({
            'v': i
        });
        temp1.push({
            'v': y[i]
        });
        temp.push({
            'c': temp1
        });
    }

});
console.log(temp);

<强>段

&#13;
&#13;
var x =
    [
        {
            x1_year: 0.73,
            x2_year: 0.84,
            x5_year: 1.37,
            x10_year: 1.88                
        }
    ];

var temp=[];
x.forEach(function(y){

  
  
  for(var i in y){
    var temp1=[]
    temp1.push({'v':i});
    temp1.push({'v':y[i]});
    temp.push({'c': temp1});
  }
  

});

console.log(temp);
&#13;
&#13;
&#13;

答案 1 :(得分:2)

这有效:

var x = [
    {
        x1_year: 0.73,
        x2_year: 0.84,
        x5_year: 1.37,
        x10_year: 1.88
    }
];
var y = [];
Object.keys(x[0]).forEach(function(key) {
    y.push({
        c: [
            {v: key},
            {v: x[0][key]}
        ]
    })
});