jquery/json - 为键创建动态数组

拉斐尔

我没有找到,如何在 jquery 中使用键数组元素的动态值创建 json 消息。

我正在尝试构建这样的 json 消息:

{
    "line": {
        "name": "Test",
        "images": [
            {
                "order": "1",
                "link": "https://google.com/1.jpg",
                "name": "1.jpg"
            },
            {
                "order": "2",
                "link": "https://google.com/2.jpg",
                "name": "2.jpg"
            }
        ]
    }
}

我无法将图片附加到消息中。

jsonObbj = {};
line = {};
line ["name"] = $("#name").val();
    
counter = 1;
$("div.carousel_image > img").each(function() {
    image = {};
    image ["order"] = counter;
    image ["name"] = $(this).attr('src');
    line ["images"].push(image); // How can I edit this image to the images array
    counter++;
});

// how can I add the line to the array

谢谢你的帮助!

德波梅罗

您需要初始化line.images为一个空数组。

jsonObbj = {};
line = {};
line ["name"] = $("#name").val();
line["images"] = []; // add this line

counter = 1;
$("div.carousel_image > img").each(function() {
    image = {};
    image ["order"] = counter;
    image ["name"] = $(this).attr('src');
    line ["images"].push(image); // How can I edit this image to the images array
    counter++;
});

请注意,通常,当您的对象键是普通字符串时,您需要使用点表示法: line.images

JSFiddle:https ://jsfiddle.net/to4xhewu/

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章