How to get key values from JsonObj
I have an object json
like this, it actually goes 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 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
}
];
+3
source to share
4 answers
function convertToLabelValue(object){
return Object.keys(object).reduce(function(acc,label){
acc.push({
"label": label,
"value": object[label]
});
return acc;
},[]);
}
Using:
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
}
]
+1
source to share
To do this with JQuery, follow these steps:
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.net/c6ojsb6c/2/
Press f12 to see the console for the final JSON.
+1
source to share