最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get key values from JsonObj - Stack Overflow

programmeradmin13浏览0评论

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
Add a ment  | 

4 Answers 4

Reset to default 5
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]})
};

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.

发布评论

评论列表(0)

  1. 暂无评论