I'm trying to write a generic function that works with JSON arrays containing arbitrary attributes. Given the following:
var propMap = '{"ddColor": "Color","ddSize": "Size", "ddOther": "Other"}'
How can I iterate through the attributes and their values without specifying either? In other words, I want to iterate the elements without specifying "ddColor", "ddSize" or "ddOther". Yet, I want to iterate both the name and its value.
I've looked all over for a solution, but can't find one and also can't make it work on jsFiddle:
var propMap = '{"ddColor": "Color","ddSize": "Size"}'
for(var x in propMap) {
// Key: x
// Value: propMap[x]
alert(x + ': ' + propMap[x]);
}
When I run the above code it seems to iterate character by character. Example:
1: C
2: o
3: l
4: o
5: r
I'm trying to write a generic function that works with JSON arrays containing arbitrary attributes. Given the following:
var propMap = '{"ddColor": "Color","ddSize": "Size", "ddOther": "Other"}'
How can I iterate through the attributes and their values without specifying either? In other words, I want to iterate the elements without specifying "ddColor", "ddSize" or "ddOther". Yet, I want to iterate both the name and its value.
I've looked all over for a solution, but can't find one and also can't make it work on jsFiddle:
var propMap = '{"ddColor": "Color","ddSize": "Size"}'
for(var x in propMap) {
// Key: x
// Value: propMap[x]
alert(x + ': ' + propMap[x]);
}
When I run the above code it seems to iterate character by character. Example:
1: C
2: o
3: l
4: o
5: r
Share
Improve this question
edited Jul 1, 2012 at 23:56
rwkiii
asked Jul 1, 2012 at 23:43
rwkiiirwkiii
5,85619 gold badges69 silver badges118 bronze badges
3
- Just to be clear, there is no such thing as a JSON array. There are JSON strings, and they can represent arrays or objects. – Jonathan M Commented Jul 1, 2012 at 23:48
-
I said you'll need to parse the JSON first if you haven't already, using
jQuery.parseJSON
. (See the bottom part of my answer, plus the jsFiddle.) – Ry- ♦ Commented Jul 1, 2012 at 23:58 - Thanks Jonathon. Wasn't sure about the right terminology. ;) – rwkiii Commented Jul 2, 2012 at 0:05
1 Answer
Reset to default 5Just use a for in
loop:
for (var x in propMap) {
if (propMap.hasOwnProperty(x)) {
// Key: x
// Value: propMap[x]
}
}
And if that's actually a string, you'll need to parse the JSON first, of course:
propMap = jQuery.parseJSON(propMap);
Here's a jsFiddle, too.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744766153a4592473.html
评论列表(0条)