简体   繁体   中英

How to store a javascript mixed array / object in json or other format and preserve the structure?

Is there any way to store a javascript mixed object / array, such as the output of a regex exec call? I noticed JSON stringify discards non numeric array properties. I can do some full object conversion magic , but is there really no other way to preserve structure?

var re = /d(b+)(d)/ig;
var result = re.exec("cdbBdbsbz");

console.log(result );
console.log( JSON.parse(JSON.stringify(result )) );

results in

["dbBd", "bB", "d", index: 1, input: "cdbBdbsbz"]
["dbBd", "bB", "d"] 

index and input are not part of the array indexes, they are properties. Simple test would show this

console.log(result[3]);     //undefined
console.log(result.index);  //1

If you coded the result manually, it would be like

var result = ["dbBd", "bB", "d"];
result.index =  1;
result.input = "cdbBdbsbz";
console.log(result);
console.log(result.toString());

If you want to get all the values, you will have to use a for in loop and build a new array adding the properties as objects.

var re = /d(b+)(d)/ig;
var result = re.exec("cdbBdbsbz");
var updatedResult = [];  //An empty array we will push our findings into
for (propName in result) {  //loop through the array which gives use the indexes and the properties
    if (!result.hasOwnProperty(propName)) { 
        continue; 
    }
    var val = result[propName];
    if(isNaN(propName)){  //check to see if it is a number [sketchy check, but works here]
        var obj = {};    //create a new object and set the name/value
        obj[propName] = val;
        val = obj;
    }
    updatedResult.push(val);  //push the number/object to the array
}
console.log(JSON.stringify(updatedResult));   //TADA You get what you expect

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