GavinBelson
GavinBelson

Reputation: 2784

Group like JSON objects into arrays

I have a model returned by a library in the following format:

var givenData = [{"fName": "john"}, {"fName": "mike"}, {"country": "USA"}]

How do I group the "fName" together and add '[]' to get:

{ 'fName[]': ['john','mike'],'country[]': ['USA'] };

**Note country and fName are not related at all.

Upvotes: 1

Views: 70

Answers (4)

mrBorna
mrBorna

Reputation: 1777

In ES6:

const newData = givenData.reduce(function (r, o) { const key = `${Object.keys(o)[0]}[]`; return { ...r, [key]: [ ...r[key], o[key] ] } }, {});

This doesn't modify your original data and is very clean.

Upvotes: 0

luiscrjr
luiscrjr

Reputation: 7268

Suggestion (using ES6 syntax)

const transformData = (data) => {
  const newData = {}
  data.forEach( (item) => {
    for (let key in item) {
       const newKey = key + "[]"
       if (!newData.hasOwnProperty(newKey)) newData[newKey] = []
       newData[newKey].push(item[key])
    }
  })
  return newData
}

/* added some extra keys just to test */
let givenData = [
  {"fName": "john", "country": "England"}, 
  {"fName": "mike"}, 
  {"country": "USA"},
  {"language": "English"}
]

console.log(transformData(givenData))
/*
{
    "fName[]": ["john","mike"],
    "country[]": ["England","USA"],
    "language[]":["English"]
}
*/

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386654

You could take the key and build an object with the key and arrays as properties.

var givenData = [{"fName": "john"}, {"fName": "mike"}, {"country": "USA"}],
    grouped = givenData.reduce(function (r, o) {
        var key = Object.keys(o)[0] + '[]';
        r[key] = r[key] || [];
        r[key].push(o[Object.keys(o)[0]]);
        return r;
    }, Object.create(null));

console.log(grouped);

Upvotes: 1

Rodrigo5244
Rodrigo5244

Reputation: 5535

You can iterate over the array and push the date to the desired field.

var givenData = [{"fName": "john"}, {"fName": "mike"}, {"country": "USA"}]

var result = {
  'fName[]': [],
  'country[]': []
};

givenData.forEach(function (data) {
  if (data.fName) {
    result['fName[]'].push(data.fName);
  }
  
  if (data.country) {
    result['country[]'].push(data.country);
  }
});

console.log(result);

Upvotes: 1

Related Questions