【问题标题】:Push item to nested array将项目推送到嵌套数组
【发布时间】:2015-04-14 06:47:40
【问题描述】:

下面是我的数组:

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

【问题讨论】:

标签: javascript jquery arrays angularjs


【解决方案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)

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-25
      • 2023-01-20
      • 1970-01-01
      相关资源
      最近更新 更多