user7600685
user7600685

Reputation:

Divide json array into json arrays based on a key

I have a json array like this:

    [
      {id:1, another_id:1},
      {id:2, another_id:1},
      {id:3, another_id:2}
    ]

Is it possible to divide this into json arrays based on the key another_id. In this case two json arrays should be created like this

  jsonArr1 = [
          {id:1, another_id:1},
          {id:2, another_id:1}
        ]

  jsonArr2 = [
          {id:3, another_id:2}
        ]

another_id will be varying. Please help guys

Upvotes: 0

Views: 2308

Answers (3)

Zainul Abideen
Zainul Abideen

Reputation: 1900

I hope the code below will work for you. As this will create two separate json arrays Arr1 for id and Arr2 for another_id

data = [
      {id:1, another_id:1},
      {id:2, another_id:1},
      {id:3, another_id:2}
    ];
    console.log(data);
    var Arr1 = [];
    var Arr2 = [];
    for(var i in data){     
        Arr1.push(data[i].id);
        Arr2.push(data[i].another_id);
    }

Upvotes: 0

trincot
trincot

Reputation: 350137

If you do not know how many different result arrays you will have, you should not try to make a variable for each of them. Instead put them in an object, where each object property corresponds to a single possible value of another_id, and the value for it is the corresponding array.

You can achieve that with reduce:

var data = [{id:1, another_id:1},{id:2, another_id:1},{id:3, another_id:2}];

var result = data.reduce( (acc, obj) => {
    acc[obj.another_id] = acc[obj.another_id] || [];
    acc[obj.another_id].push(obj);
    return acc;
}, {});

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

Upvotes: 3

void
void

Reputation: 36703

If you want different variables then you can build a function which will return filtered array based on the passed value. This will use Array.filter()

function formatData(check) {
  var data = [{
      id: 1,
      another_id: 1
    },
    {
      id: 2,
      another_id: 1
    },
    {
      id: 3,
      another_id: 2
    }
  ];

  return data.filter(el => el.another_id === check);
}

jsonArr1 = formatData(1);
jsonArr2 = formatData(2);

console.log(jsonArr1);
console.log(jsonArr2);

Upvotes: 1

Related Questions