admin管理员组文章数量:1392007
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.
本文标签: javascriptGet element attribute names from JSONStack Overflow
版权声明:本文标题:javascript - Get element attribute names from JSON - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744766152a2624053.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论