1

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"] 
Community
  • 1
  • 1
giorgio79
  • 3,787
  • 9
  • 53
  • 85
  • index and input are not part of the array indexes, they are properties `console.log(result[3]); console.log(result.index);` – epascarello Aug 27 '14 at 19:22
  • You can do stuff like `{"0":"dbBd", "1":"bB", "2":"d", "index": 1, "input": "cdbBdbsbz"}` but then it wont have array properties like `length`. – tcooc Aug 27 '14 at 19:44

1 Answers1

0

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
epascarello
  • 204,599
  • 20
  • 195
  • 236