0

I didn't find out, how to create a json message in jquery with dynamic values for a key array element.

I'm trying to build a json message like this:

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

I fail to attach the pictures to the message.

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

Thx for your help!

asked Sep 15, 2021 at 23:37
0

2 Answers 2

1

You need to initialize line.images to an empty array.

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++;
});

Note, in general, when your object keys are normal strings, you want to use dot notation: line.images

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

answered Sep 15, 2021 at 23:45
Sign up to request clarification or add additional context in comments.

Comments

0

You need to initialise line.images as an array before you can start pushing to it. You should also make sure you declare your variables properly with const, let or var or else they will be implicitly global.

Try this for a simple, object literal initialiser alternative

const jsonObbj = {
 line: {
 name: $("#name").val(),
 images: $("div.carousel_image > img").map((i, img) => ({
 order: i + 1,
 name: img.getAttribute("src"),
 link: img.src
 })).get()
 }
}

See https://api.jquery.com/map/

answered Sep 16, 2021 at 0:04

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.