简体   繁体   English

如何将值添加到JSON对象?

[英]How to add values to a JSON object?

I have created an array with: 我创建了一个数组:

var msg = new Array();

then, I have a function that add values to this array, this function is: 那么,我有一个为这个数组添加值的函数,这个函数是:

function add(time, user, text){
    var message = [time, user, text];
    if (msg.length >= 50)
        msg.shift();

    msg.push(message);        
}

As you can see, if the array has 50 or more elements I remove the first with .shift() . 如您所见,如果数组包含50个或更多元素,我将使用.shift()删除第一个元素。 Then I add an array as element. 然后我添加一个数组作为元素。

Ok, the code works perfectly, but now I have to loop the msg array to create a JSON obj. 好的,代码运行完美,但现在我必须循环msg数组来创建一个JSON obj。

The JSON object should has this format: JSON对象应具有以下格式:

var obj = [
{'time' : time, 'user' : user, 'text' : text},
{'time' : time, 'user' : user, 'text' : text},
{'time' : time, 'user' : user, 'text' : text}
]

I mean...i have to loop msg array and then store all the values inside the JSON object. 我的意思是...我必须循环msg数组,然后将所有值存储在JSON对象中。 I do not know how to "concatenate" the element of the array inside json obj. 我不知道如何在json obj中“连接”数组元素。

Could you help me? 你可以帮帮我吗?

Thank you very much in advance! 非常感谢你提前!

I'll give you an example from your add function: 我将从你的添加功能给你一个例子:

function add(time, user, text){
    // this line is all I changed
    var message = {'time' : time, 'user' : user, 'text' : text};

    if (msg.length >= 50)
        msg.shift();

    msg.push(message);        
}

As you can see the message variable is no longer an array but it's the Object you want it to be. 正如您所看到的,消息变量不再是一个数组,而是它想要的对象。

From this you should be able to work out how to create a new array and add the values you want to it. 从这里你应该能够找出如何创建一个新数组并添加你想要的值。

Try this: 尝试这个:

var len = msg.length;
var obj = [];
for (var i = 0; i < len; i++) {
    var item = {
        'time': msg[i][0],
        'user': msg[i][1],
        'text': msg[i][2]
    }
    obj.push(item);
}

I think you want something like this: 我想你想要这样的东西:

function add(time, user, text){
  var message = {time:time, user:user, text:text};
  if (msg.length >= 50)
    msg.shift();

  msg.push(message);        
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM