0

i get data named dataFromServer from server in this format.

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

and i want to change into this format

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

im doing this to get data in required format

var jsonObjLoop = '{';
var item = '"Alpha" :[';
$.each(dataFromServer, function (idx, val) {
    item += '{"Name":"' + val.NAME + '"},';
});
item += ']}';
jsonObjLoop += item;
console.log(jsonObjLoop);
Shaybi
  • 318
  • 2
  • 9
  • `jsonObj["Alpha"]` – Mahi Dec 06 '16 at 10:45
  • This question doesn't make any sense. Please update it with your real situation. You've said *"but when i assign this string to a variable and console it then it displays correctly formatted json "* but assigning the string to a variable and console logging it is **exactly** what you do in your first example. – T.J. Crowder Dec 06 '16 at 10:45
  • please add the data of `dataFromServer` and the wanted result in text form. – Nina Scholz Dec 06 '16 at 10:46
  • 1
    Side note: Don't create JSON via string concatenation. It's error-prone and unnecessary. – T.J. Crowder Dec 06 '16 at 10:46
  • you can just create this as a javascript object, and then stringify it to display it. Building it up using strings is much more likely to result in bugs. Why are you making this complicated, when the language has a built-in way to do this task? – ADyson Dec 06 '16 at 10:50
  • i have edited the question. hope it is clear. apologize for vague statement in the first place – Shaybi Dec 06 '16 at 11:15
  • Possible duplicate of [Access / process (nested) objects, arrays or JSON](http://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json) – Liam Dec 06 '16 at 11:16
  • @ADyson im newbie, i searched alot on internet and came up with this solution. thanks for suggesting JavaScript object. i try for that. – Shaybi Dec 06 '16 at 11:18

2 Answers2

1

You could use the data array and iterate it. Then use an object for grouping and assign a new object to the group of the parent.

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; }

Version with variable property to group on

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; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • that's the exact answer i wanted @Nina. appreciate that you understood my problem, one more thing please, can i put `Parent` in a variable and use that variable instead of using `Parent` word. like: `var groupBy = 'Parent'` and `grouped[a.groupBy]`. i tried it but it does't work :-( – Shaybi Dec 07 '16 at 05:07
  • @Shaybi, plaese see version 2. the new objects are now dynamic created without the grouping key. – Nina Scholz Dec 07 '16 at 07:38
  • awesome. hope i will find u next time when needed:-) – Shaybi Dec 07 '16 at 08:10
  • you could upvote and/or accept the answer you helped (most), please have a look here: http://stackoverflow.com/help/someone-answers – Nina Scholz Dec 07 '16 at 08:17
0

Try 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);
Debug Diva
  • 26,058
  • 13
  • 70
  • 123