简体   繁体   中英

JavaScript convert array to JSON format

I have an array like

["categories", 1, "categories", 2, "categories", 3]

I want to convert this array to JSON format like

{"categories":1,"categories":2, "categories":3}

You can convert an array into JSON with:

var a = ["categories", 1, "categories", 2, "categories", 3];
var json = JSON.stringify(a);
// json will be: "["categories",1,"categories",2,"categories",3]"

The JSON string you have in your question is not an array, it is an object. And as Pranav pointed out in his comment, it is an invalid object notation, because the properties of an object have to be unique.

In such case We will have to go through {"categories": [1,2,3]} . for this we have to create a array of values and create a JSON data {"categories": [1,2,3]} .

This solves the problem to post multiple values of same field like checkbox through ajax.

if you means this

["categories1", 1, "categories2", 2, "categories3", 3]

each key is different, then you can go with

var a = ["categories1", 1, "categories2", 2, "categories2", 3],
    b = {}, len = a.length;

for(i=0; i<len; i+=2){
    var key = a[i], val = a[i+1];
    b[key] = val
}

// b should be {"categories1":1,"categories2":2, "categories3":3}

if not, just like @Pranav C Balan said, you can't have three identical keys in one object, they will simply override the previous ones;

you might also need this underscore method, really handy

_.object(['moe', 'larry', 'curly'], [30, 40, 50]);
=> {moe: 30, larry: 40, curly: 50}

_.object([['moe', 30], ['larry', 40], ['curly', 50]]);
=> {moe: 30, larry: 40, curly: 50}

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