将数据推送到 JSON 对象 javascript

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19101434/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 14:21:32  来源:igfitidea点击:

Pushing data to JSON object javascript

javascript

提问by Abhi

I want to push this object to a JSON array

我想将此对象推送到 JSON 数组

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 .

由于我的 JSON 键值是动态的,我无法使用键访问,所以我使用了循环方法。

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.

当我提醒值时,我正确地获取了键和值,但是当我将它推送到数组时,我的键总是作为“键”出现,而不是像代码中的 x、y、z 这样的实际键。

Any help is appreciated.

任何帮助表示赞赏。

回答by ThiefMaster

The 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);

回答by PSL

You need to use []notation, otherwise always the key name will be keyand not the value of the key.

您需要使用[]符号,否则总是键名将是key而不是键的值。

 str.xA.push({
     key :   obj[key]
 })

to

   var tmp= {};
   tmp[key] = obj[key]
   str.xA.push(tmp)