0

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?

1
  • 1
    Anything is possible. This certainly is.. have you made an attempt to solve it? Commented May 27, 2015 at 20:55

1 Answer 1

3

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.

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.