2

I want to transform following format JSON:

{
    id1: value1,
    id2: value2
    id3: value3,
    ...
} 

into

[    
    { id: 'id1', value: 'value1' },
    { id: 'id2', value: 'value2' },
    { id: 'id3', value: 'value3' },
    ...
]

What would be fast and convenient? Is there any way we can use underscore.js for this. Thank you in advance.

7 Answers 7

3

You can use the map method provided by underscore.

  var input = {
    "id1": "value1",
    "id2": "value2"
  };

  var output = _.map(input, function (value, key) {
    return {id: key, value: value};
  });
Sign up to request clarification or add additional context in comments.

1 Comment

Yes. Actully i am using underscore and it works..Thanks :)
2

Something like:

var arr = Object.keys(obj).map(k => ({id:k, value:obj[k]}));

no underscore required ;-) If you're not using babel or something similar you might need to write:

var arr = Object.keys(obj).map(function (k) { return {id:k, value:obj[k]};});

Comments

1

User the following:

var arr = [];

var obj = {
    id1: "42",
    id2: "hello",
    id3: 6,
}

for (var i in obj) {
    arr.push({id: i, value: obj[i]});
}

Alternatively:

Object.keys(obj).map(function(value, index) {
   return {id: value, value: obj[value]}
})

Comments

0

Couldn't you just parse it using:

var object = JSON.parse(jsonString);

If that doesn't produce the desired result then just iterate through your string and manually add in the keys.

Comments

0

You should use Object.prototype.hasOwnProperty to ensure that you are only adding the keys that are directly set on obj:

var arr = [];
for (var key in object) {
    if (object.hasOwnProperty(key)) {
        arr.push({ id: key, value: object[value] });
    });
}

Comments

0

Using underscore, you could do this with the map method:

var obj = {
    id1: 'value1',
    id2: 'value2',
    id3: 'value3',
}

//with underscore, transforming the array
_.map(obj, function(value,key){
    return({
    id: key.toString(),
    value: value
  })
})
//obj = Object {id1: "value1", id2: "value2", id3: "value3"}

Here's a jsfiddle to test

Underscore map

Comments

0

There is simple and efficient way to do it with underscore lib. Please try it:

_.map({id1: value1, id2: value2}, function(value, key) {
    return {id: key, value: value};
});

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.