I have a json
object like this actually it is ing dynamically.
For example we can use this Json object.
var JsonObj= { "one":1, "two":2, "three":3, "four":4, "five":5 };
But i want to change it some thing like this using javascript
or jquery
.
var sample = [
{
"label":"one",
"value":1
},
{
"label":"two",
"value":2
},
{
"label":"three",
"value":3
},
{
"label":"four",
"value":4
},
{
"label":"five",
"value":5
}
];
I have a json
object like this actually it is ing dynamically.
For example we can use this Json object.
var JsonObj= { "one":1, "two":2, "three":3, "four":4, "five":5 };
But i want to change it some thing like this using javascript
or jquery
.
var sample = [
{
"label":"one",
"value":1
},
{
"label":"two",
"value":2
},
{
"label":"three",
"value":3
},
{
"label":"four",
"value":4
},
{
"label":"five",
"value":5
}
];
Share
Improve this question
asked Jun 26, 2015 at 14:29
Shrinivas PaiShrinivas Pai
7,7214 gold badges32 silver badges57 bronze badges
4 Answers
Reset to default 5var JsonObj= { "one":1, "two":2, "three":3, "four":4, "five":5 };
var arr = [];
for(property in JsonObj) {
arr.push(
{"label":property,
"value":JsonObj[property]})
};
You can achieve that by using the Object.keys
method
var keys = Object.keys(myJSONObject);
function convertToLabelValue(object){
return Object.keys(object).reduce(function(acc,label){
acc.push({
"label": label,
"value": object[label]
});
return acc;
},[]);
}
Usage:
convertToLabelValue({ "one":1, "two":2, "three":3, "four":4, "five":5 })
Output:
[
{
"label": "one",
"value": 1
},
{
"label": "two",
"value": 2
},
{
"label": "three",
"value": 3
},
{
"label": "four",
"value": 4
},
{
"label": "five",
"value": 5
}
]
To do it with JQuery try below:
var JsonObj= { "one":1, "two":2, "three":3, "four":4, "five":5 };
var sample = [];
$.each(JsonObj, function(key, val){
sample.push({'label': key, 'value': val});
});
Here is a jsfiddle - https://jsfiddle/c6ojsb6c/2/
Hit f12 to see the console for final JSON.