解析使用每个循环创建的json对象

时间:2016-12-06 10:43:29

标签: javascript jquery arrays json

我以这种格式从服务器获取名为dataFromServer的数据。

[
{"Name":"txtFirstName","Parent":"Alpha"},
{"Name":"txtLastName","Parent":"Alpha"},
{"Name":"btnSESearch","Parent":"Alpha"},
{"Name":"tblfootblSearchPat","Parent":"Bravo"},
{"Name":"btn-action-SPG-delete","Parent":"Bravo"}
]

我希望换成这种格式

{ 
"Alpha": 
[
{ "Name": "txtFirstName" }, 
{ "Name": "txtLastName" }, 
{ "Name": "btnSESearch" }, 
],
"Bravo":
[
{ "Name": "tblfootblSearchPat" }, 
{ "Name": "btn-action-SPG-delete" }, 
]
}

我这样做是为了获取所需格式的数据

var jsonObjLoop = '{';
var item = '"Alpha" :[';
$.each(dataFromServer, function (idx, val) {
    item += '{"Name":"' + val.NAME + '"},';
});
item += ']}';
jsonObjLoop += item;
console.log(jsonObjLoop);

2 个答案:

答案 0 :(得分:1)

您可以使用数据数组并迭代它。然后使用对象进行分组,并将新对象分配给父组。



var data = [{ Name: "txtFirstName", Parent: "Alpha" }, { Name: "txtLastName", Parent: "Alpha" }, { Name: "btnSESearch", Parent: "Alpha" }, { Name: "tblfootblSearchPat", Parent: "Bravo" }, { Name: "btn-action-SPG-delete", Parent: "Bravo" }],
    grouped = Object.create(null);

data.forEach(function (a) {
    grouped[a.Parent] = grouped[a.Parent] || []; // checks if parent exist, if not create array
    grouped[a.Parent].push({ Name: a.Name });
});

console.log(grouped);

.as-console-wrapper { max-height: 100% !important; top: 0; }




具有可变属性的版本,可以分组



function groupBy(array, key) {
    var grouped = Object.create(null);
    data.forEach(function (a) {
        var o = Object.create(null);
        Object.keys(a).forEach(function (k) {
            if (k !== key) {
                o[k] = a[k];
            }
        });
        grouped[a[key]] = grouped[a[key]] || [];
        grouped[a[key]].push(o);
    });
    return grouped;
}

var data = [{ Name: "txtFirstName", Parent: "Alpha" }, { Name: "txtLastName", Parent: "Alpha" }, { Name: "btnSESearch", Parent: "Alpha" }, { Name: "tblfootblSearchPat", Parent: "Bravo" }, { Name: "btn-action-SPG-delete", Parent: "Bravo" }];

console.log(groupBy(data, 'Parent'));
console.log(array);

.as-console-wrapper { max-height: 100% !important; top: 0; }




答案 1 :(得分:0)

尝试for in loop

var dataFromServer = [
{"Name":"txtFirstName","Parent":"Alpha"},
{"Name":"txtLastName","Parent":"Alpha"},
{"Name":"btnSESearch","Parent":"Alpha"},
{"Name":"tblfootblSearchPat","Parent":"Bravo"},
{"Name":"btn-action-SPG-delete","Parent":"Bravo"}
];

var newObj = {};

for (var i in dataFromServer) {
  newObj[dataFromServer[i].Parent] = newObj[dataFromServer[i].Parent] || [];
  newObj[dataFromServer[i].Parent].push({ "Name": dataFromServer[i].Name});
}

console.log(newObj);