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


var JsonObj= { "one":1, "two":2, "three":3, "four":4, "five":5 };
var arr = [];
for(property in JsonObj) {
    arr.push(
             {"label":property, 
             "value":JsonObj[property]})
};

      



+5


source


You can achieve this using the method Object.keys



var keys = Object.keys(myJSONObject);

+1


source


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 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







All Articles