繁体   English   中英

将项目推送到嵌套数组

[英]Push item to nested array

下面是我的数组:

[{
    "album_desc": "Test",
    "id": 1,
    "album_title": "Test",
    "ImageName": "image004.png",
    "album_pics": [{
        "media_type": "image/png",
        "last_modified_date": 1428913015000,
        "thumnail_pic_loc": "image004.png",
        "large_pic_loc": "image004.png",
        "filter_type": "image/png",
        "pic_id": "d5bd"
    }]
}]

我需要将数组的结构更改为如下所示。 上传图片时如何动态使用? 如何将数组推入数组? 有什么建议么?

{
    "album_desc": "Album 1",
    "id": "399234688",
    "album_title": "Album 1",
    "album_pics": [{
        "media_type": "image",
        "last_modified_date": "2015-01-16T00:40:39.071Z",
        "thumnail_pic_loc": "3fe2a54346b3d54e-pinaki2.jpg",
        "large_pic_loc": "3fe2a54346b3d54e-pinaki2.jpg",
        "filter_type": "image/jpeg",
        "pic_id": "d5bc"
    }, {
        "media_type": "image",
        "last_modified_date": "2015-01-16T00:40:39.071Z",
        "thumnail_pic_loc": "3fe2a54346b3d54e-pinaki3.jpg",
        "large_pic_loc": "3fe2a54346b3d54e-pinaki3.jpg",
        "filter_type": "image/jpeg",
        "pic_id": "d5bd"
    }],
}

我的理解是,您想向album_pics数组添加一个新元素。

var myArray = [{"album_desc": "Test",...}]

var newPicture = {"media_type": "image",... }

myArray[0].album_pics.push(newPicture);

myArray是您的原始数组, newPicture是您要添加到album_pics数组的图片。 在此示例中,我修改了myArray的第一个元素,但它可以是任何元素,例如: myArray[5].album_pics.push(newPicture)

使用Array.push

var arr = [{
    name: "foo",
    age: 35,
    friends: [{
      name: "zee",
      age: 13
    }]
  }];

  arr[0]['friends'].push({
    name: "boo",
    age: 22
  });


  /*
    result 
    [{
      "name": "foo",
      "age": 35,
      "friends": [{
        "name": "zee",
        "age": 13
      }, {
        "name": "boo",
        "age": 22
      }]
    }]
  */

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/push

暂无
暂无

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

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