我怎样才能推入嵌套数组?

时间:2018-11-01 16:30:19

标签: javascript jquery

我正在尝试将其插入嵌套,如下所示:

[{
  "chatid": 10000414,
  "connected": true,
  "index": 0,
  "jsonedUser": {},
  "membership": "",
  "messages": [{
    "chatid": 10000414,
    "createdOn": "2018-10-29T16:50:44.4900000",
    "isArchive": false,
    "isNew": false,
    "message": "great",
    "messageid": 3,
    "sentby": {
      "id": 59,
      "name": "Ana"
    }
  }, {
    "chatid": 10000414,
    "createdOn": "2018-10-25T13:49:50.9900000",
    "isArchive": false,
    "isNew": false,
    "message": "hi",
    "messageid": 2,
    "sentby": {
      "id": 59,
      "name": "Ana"
    }
  }, {
    "chatid": 10000414,
    "createdOn": "2018-10-31T10:20:59.5000000",
    "isArchive": false,
    "isNew": false,
    "message": "hello there",
    "messageid": 1,
    "sentby": {
      "id": 91,
      "name": "Miliam"
    }
  }],
  "opened": true,
  "port": 10842,
}]

我尝试将类似的对象推入消息内[]我不知道该怎么办,因为有人可以帮助我

我尝试像这样

var chat =  { chatid: 10000414, createdOn: "2018-10-29T16:50:44.4900000", isArchive: false, isNew: false, message: val, messageid: 3, sentby: {id:59, name:"betsynray"} }
    var newSingleChat = singleChat[0].messages.push(val);

但是当我使用newSingleChat时,您会显示“ 4”

2 个答案:

答案 0 :(得分:0)

您似乎对Array#pushArray#concat感到困惑。

.push()将修改原始数组并返回新长度。

var array = [1, 2, 3];
var result = array.push("a");
// array: [1, 2, 3, "a"]
// result: 4

.concat()将基于旧数组和新值返回一个新数组。

var array = [1, 2, 3];
var result = array.concat("a");
// array: [1, 2, 3]
// result: [1, 2, 3, "a"]

答案 1 :(得分:0)

谢谢,我使用

解决了这个问题
var newSingleChat = singleChat[0].messages.concat(chat);

现在一切正常,这要感谢@James Long的所有帮助