sainu sainu - 1 month ago 8
JSON Question

Convert array structure

Hi I want to convert an array from the format

tableValue= [{typeID:"1",name:"xxxxx"},
{typeID:"1",name:"aaaaa"},
{typeID:"1",name:"bbbbb"},
{typeID:"2",name:"ccccc"},
{typeID:"2",name:"ddddd"},
{typeID:"2",name:"fffff"},
{typeID:"3",name:"ttttt"},
{typeID:"3",name:"yyyyy"},
{typeID:"4",name:"zzzzz"},
{typeID:"4",name:"hhhhh"}]


to the format

tableGroup=["fk_type1":[{typeID:"1",name:"xxxxx"},{typeID:"1",name:"aaaaa"},{typeID:"1",name:"bbbbb"}],
"fk_type2":[{typeID:"2",name:"ccccc"},{typeID:"2",name:"ddddd"},{typeID:"2",name:"fffff"}],
"fk_type3":[{typeID:"3",name:"ttttt"},{typeID:"3",name:"yyyyy"}],
"fk_type4":[{typeID:"4",name:"zzzzz"},{typeID:"4",name:"hhhhh"}]]


updation
My Component is as follows:

createTableValues() {
let groups = {};
tableValue.forEach(item => {
if (tableGroup[item.typeID]) {
tableGroup[item.typeID].push(item);
} else {
tableGroup[item.typeID] = [{ 'fk_type'+item.typeID }];
}
});
}


Thanks in advance

Answer

The one you expect is not a valid array.

It should be like this,

{"fk_type1":[{typeID:"1",name:"xxxxx"},{typeID:"1",name:"aaaaa"},{typeID:"1",name:"bbbbb"}],
"fk_type2":[{typeID:"2",name:"ccccc"},{typeID:"2",name:"ddddd"},{typeID:"2",name:"fffff"}],
"fk_type3":[{typeID:"3",name:"ttttt"},{typeID:"3",name:"yyyyy"}],
"fk_type4":[{typeID:"4",name:"zzzzz"},{typeID:"4",name:"hhhhh"}]}

And the code is,

var items = [{typeID:"1",name:"xxxxx"},
{typeID:"1",name:"aaaaa"},
{typeID:"1",name:"bbbbb"},
{typeID:"2",name:"ccccc"},
{typeID:"2",name:"ddddd"},
{typeID:"2",name:"fffff"},
{typeID:"3",name:"ttttt"},
{typeID:"3",name:"yyyyy"},
{typeID:"4",name:"zzzzz"},
{typeID:"4",name:"hhhhh"}];

var output = {};
var key = 'fk_type';

items.forEach(function(item){
  var typeID = item.typeID;
  if(!output[key + typeID]) {
    output[key + typeID] = [];
  }
  
  output[key + typeID].push(item);
});

console.log(output);