0

我想采用格式如下的 JavaScript 对象:

results = {
   names: [
        "id",
        "first_name"
        ],
    values: [
        [
            1234,
            "Fred"
        ],
        [
            4321,
            "Joe"
        ],
        [
            1123,
            "Mary"
        ]
    ]
}

变成这样:

    results = {
        [id: 1234, name: "Fred"],
        [id: 4321, name: "Joe"],
        [id: 1123, name: "Mary"]
    }

我尝试做这样的事情,但我无法得到正确的结构:

var data = []
for (i=0; i < results['values'].length; i++ ){
    var innerData = []
    for (b=0; b < results['names'].length; b++ ){
        innerData.push([name:results['names'][b], value: results['values'][i][b]])
    }
    data.push(innerData)
}
console.log(data)
4

2 回答 2

2

问题1:

results = {
    [id: 1234, name: "Fred"],
    [id: 4321, name: "Joe"],
    [id: 1123, name: "Mary"]
}

var data = []

[name:results['names'][b]…

数组[]按顺序包含一组值。

一个对象{}由一组key:value对组成。

你每次都用错了。{}在你有的地方使用,[]反之亦然


问题2:

您说您想要带有idname键的对象,但您正在尝试创建namevalue键。使用您真正想要的属性名称。

于 2013-11-04T08:31:46.037 回答
0

尝试这个:

var data = [];
for (i in results['values']){
    var innerData = {}
    var value = results['values'][i];
    for (b in value){
        var key = results['names'][b];
        innerData[key] = value[b]; 
    }
    data.push(innerData);
}
console.log(data);
于 2013-11-04T08:47:24.040 回答