1

试图将 javascript 对象拆分为哈希数组。我必须根据符号“|”的出现来拆分数组内的内容

我的输入数组看起来像

{
      "testFieldNames": ["testNumber", "testName", "testDate1", "testDate2"]
},
"data": [
    "4|Sam|2012-02-10T00:00Z",
    "0|Wallace|1970-01-01T00:00Z|2012-02-10T00:00Z"
 ]
};

并且预期的输出是[{"testNumber" : "4", "testName" : "Sam", "testDate1" : "2012-02-10T00:00Z", "testDate2" : "0"},{"testNumber" : "0", "testName" : "Wallace", "testDate1" : "1970-01-01T00:00Z", "testDate2" : "2012-02-10T00:00Z"}]

这是我尝试过的..但它并不完整。

http://jsfiddle.net/Dwfg​​6/1/

4

4 回答 4

3
var header = responseData.header.testFieldNames,
    length = header.length,
    result;
result = responseData.data.map(function(el) {
    var ret = {}, data = el.split('|'), i;
    for (i=0; i < length; i++) {
      ret[header[i]] = data[i];
    }
    return ret;
});

console.log(result);

演示。注意:您可以使用 jQuery.map 方法代替旧浏览器。

于 2012-10-11T11:20:45.983 回答
0

你很亲近...

http://jsfiddle.net/Dwfg​​6/4/

于 2012-10-11T11:24:06.263 回答
0
var responseData = {
    "header": {
        "testFieldNames": ["testNumber", "testName", "testDate1", "testDate2"]
    },
    "data": [
        "4|Sam|2012-02-10T00:00Z|2012-02-10T00:00Z",
        "0|Wallace|1970-01-01T00:00Z|2012-02-10T00:00Z"
        ]
};


function buildData(fields, data) {
    var output = [];
    if (fields && fields.length && data && data.length) {
        for (var i = 0; i < data.length; i++) {
            var row = data[i].split("|");
            output[i] = {};
            while (row.length) {
                output[i][fields[4 - row.length]] = row.shift();
            }
        }
    }
    return output;
}

console.log(buildData(responseData.header.testFieldNames, responseData.data));

小提琴:http: //jsfiddle.net/FjJse/1/

于 2012-10-11T11:36:48.940 回答
0

我的答案:

小提琴

function mapData (data) {
    'use strict';

    var result=[];
    var i, j;
    var values = [];
    var resultObj;

    for(i=0; i < data.testFieldValues.length; i += 1) {
        values = data.testFieldValues[i].split("|");
        resultObj = {};
        for(j = 0; j < data.testFieldNames.length; j += 1) {
            resultObj[data.testFieldNames[j]] = values[j];
        }
        result.push(resultObj);
    }
    return result;
}

//$(document).ready(function() {
//    'use strict';

    var data = {testFieldNames: ["testNumber", "testName", "testDate1", "testDate2"],
                testFieldValues: [
                    "4|Sam|2012-02-10T00:00Z|2012-02-10T00:00Z",
                    "0|Wallace|1970-01-01T00:00Z|2012-02-10T00:00Z"
                ]
               };

    console.log(mapData(data));
//});
    /*Expected Output [{"testNumber" : "4", "testName" : "Sam", "testDate1" : "2012-02-10T00:00Z", "testDate2" : "2012-02-10T00:00Z"},{"testNumber" : "0", "testName" : "Wallace", "testDate1" : "1970-01-01T00:00Z", "testDate2" : "2012-02-10T00:00Z"}]*/

在 Chrome 中按 F12 以查看控制台,或在 FireFox 中打开 FireBug 或在 Opera 中打开 LadyBug 等。

于 2012-10-11T12:16:17.177 回答