简体   繁体   中英

How to simplify Json Keys?

I have Json object as follows

var data= {
            "10":"One",
            "11":"One",
            "12":"One",
            "13":"One",            

            "20":"Two",
            "21":"Two",
            "22":"Two",
            "23":"Two",            
        }

Is there any way that I can simplify like

var data= {
            "10-13":"One",

            "20-23":"Two",         
        }

Thanks

Using only the data you've provided, I'm inclined to say that your object is upside-downus, back-to-frontus.

var data = {
    "One" : [10,11,12,13],
    "Two" : [20,21,22,23]
};

But, it depends entirely on how you're using this data! In all likelihood, the structure you have now is the right one for the job. I don't know, how would I know?

Side-note: There is no such thing as a "Json object". JSON is a string that represents an object in a syntax that is compatible with JavaScript.

Eg:

var data = {
    "10-13": "One",
    "20-23": "Two"
}
var result = {};
for (range in data) {
    ends = range.split('-');
    ends.length === 1 && ends.push(ends[0]);
    for (var n = parseInt(ends[0]); n < parseInt(ends[1]) + 1; n++) {
        result[String(n)] = data[range];
    }
}
console.debug(result);

gives:

{10: "One", 11: "One", 12: "One", 13: "One", 20: "Two", 21: "Two", 22: "Two", 23: "Two"} 

in your favorite browser go into web developer mode and just paste in:

var obj={};
for(var k=startYouWant; k< lengthYouWant+startYouWant; k++){
    var ks = k.toString();
    obj[k]="one";
}

then do JSON.stringify(obj);

then copy that into the code you're actually working on :)

HTH

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM