0

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

1
  • Show us what you've done so far :) Commented Nov 7, 2016 at 9:01

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.