user3314402
user3314402

Reputation: 254

How to Re-format this JSON using Lodash / JavaScript?

I need to reformat the following JSON data

[
  {
    "name": "Hello",
    "value": 1
  },
  {
    "name": "Hello",
    "value": 11
  },
  {
    "name": "Bye",
    "value": 2
  },
  {
    "name": "Bye",
    "value": 22
  }
]

to this:

[
  {
     "Hello": 1,
     "Bye": 2
  },
  {
     "Hello": 11,
     "Bye": 22
  },
]

There will always be an object with the same "name" field (but a different value in the "value" field) right after. I am stuck and not sure how to solve this. Is it possible to do using Lodash or pure JavaScript?

Upvotes: 0

Views: 101

Answers (1)

Siguza
Siguza

Reputation: 23850

I have never before heard of Lodash, but in pure JS this can be solved with two nested loops:

function myConvert(long)
{
    var short = [];
    for(var i = 0; i < long.length; i++)
    {
        var key = long[i].name;
        var value = long[i].value;
        var object = null;
        for(var j = 0; j < short.length; j++)
        {
            if(short[j][key] === undefined)
            {
                object = short[j];
                break;
            }
        }
        if(object === null)
        {
            object = {};
            short.push(object);
        }
        object[key] = value;
    }
    return short;
}

This is basically:

Iterate over all elements of long.
For each of those, iterate over all elements of short to find the first element where the current name as key is not defined.
Create a new object, if not found.
Add the current value to object with name as key.

Upvotes: 3

Related Questions