admin管理员组文章数量:1221312
I want to push this object to a JSON array
var obj = {'x':21,'y':32,'z':43};
Since my JSON key:value comes dynamically , I cant access using keys , so i used the loop method .
var str = {xA : []}; //declared a JSON array
for (var key in obj) {
alert(' name=' + key + ' value=' + obj[key]);
str.xA.push({
key : obj[key]
})
}
When i alert the values I am getting the keys and values properly, but when I am pushing it to the array my key is always coming as 'key' instead of the actual key like x, y,z as in the code.
Any help is appreciated.
I want to push this object to a JSON array
var obj = {'x':21,'y':32,'z':43};
Since my JSON key:value comes dynamically , I cant access using keys , so i used the loop method .
var str = {xA : []}; //declared a JSON array
for (var key in obj) {
alert(' name=' + key + ' value=' + obj[key]);
str.xA.push({
key : obj[key]
})
}
When i alert the values I am getting the keys and values properly, but when I am pushing it to the array my key is always coming as 'key' instead of the actual key like x, y,z as in the code.
Any help is appreciated.
Share Improve this question edited Sep 30, 2013 at 18:44 ThiefMaster 319k85 gold badges603 silver badges645 bronze badges asked Sep 30, 2013 at 18:41 AbhiAbhi 6,5787 gold badges43 silver badges60 bronze badges 2- 3 It's a JavaScript object literal, NOT JSON. – ThiefMaster Commented Sep 30, 2013 at 18:42
- 1 Please, don't use the word "JSON", there's no JSON at all here. – Denys Séguret Commented Sep 30, 2013 at 18:43
2 Answers
Reset to default 10The literal notation does not allow expressions for keys. You need to create the object first and then use the bracket notation instead:
var tmp = {};
tmp[key] = obj[key];
str.xA.push(tmp);
You need to use []
notation, otherwise always the key name will be key
and not the value of the key.
str.xA.push({
key : obj[key]
})
to
var tmp= {};
tmp[key] = obj[key]
str.xA.push(tmp)
本文标签: Pushing data to JSON object javascriptStack Overflow
版权声明:本文标题:Pushing data to JSON object javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1739343156a2159031.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论