0

I want to extract the three variables (friendCount, pnCount, and allCount) out of a string representation of the following Object:

'{"friendCount":5,"pnCount":0,"allCount":5}'

I thought about using a RegEx or similar, but I have no further Idea. The numbers in the string may be between 0 and about 100

Gykonik
  • 638
  • 1
  • 7
  • 24

3 Answers3

7

If that is a string, than parse it...

var str = '{"friendCount":5,"pnCount":0,"allCount":5}';
var obj = JSON.parse(str);
console.log(obj.friendCount, obj.pnCount, obj.allCount);

If it is already an object, just reference it

var obj = {"friendCount":5,"pnCount":0,"allCount":5};
console.log(obj.friendCount, obj.pnCount, obj.allCount);
epascarello
  • 204,599
  • 20
  • 195
  • 236
1

Try this

var data= {"friendCount":5,"pnCount":0,"allCount":5}

var friendCount = data.friendCount;
var pnCount = data.pnCount;
var allCount = data.allCount;
Anoop LL
  • 1,548
  • 2
  • 21
  • 32
0

If you want Regex it can be done like this:

var re = /([\w]+)":(\d+)/g; 
var str = '"friendCount":5,"pnCount":0,"allCount":5';
var m;

while ((m = re.exec(str)) !== null) {
    if (m.index === re.lastIndex) {
        re.lastIndex++;
}
// View your result using the m-variable.
// eg m[0] etc.

}

Aferrercrafter
  • 319
  • 1
  • 6
  • 14