将项目推送到嵌套数组

时间:2015-04-14 06:47:40

标签: javascript jquery arrays angularjs

下面是我的数组:

[{
    "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"
    }],
}

2 个答案:

答案 0 :(得分:1)

我的理解是你想在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)

答案 1 :(得分:0)

使用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