The Dead Man
The Dead Man

Reputation: 5566

How to dynamically add id property in an array of objects?

I have a simple section in which a user can add movie details using a form. I am taking the values entered by the user and creating an object from them which I pushing in to an array. However I also want to include a dynamic ID for each added movie.

$("#btnAddMovie").click(function(e) {
  console.log('btn-movie triggered');

  var jsonData = [];
  var formData = $("#movieForm").serializeArray();

  $.each(formData, function() {
    console.log(formData);
    jsonData.push({
      title: formData[0].value,
      movieurl: formData[1].value,
      movieid: '1'
    });
  });

  console.log(jsonData);

  var params = JSON.stringify({
    movies: jsonData
  });

  $.ajax({
    type: 'POST',
    data: {
      params: params
    },
    url: 'save_to_json.php',
    success: function(data) {
      $('#msg').html(data).fadeIn('slow');
      $('#msg').delay(2000).fadeOut('slow');
    },
    error: function() {
      $('#error-msg').html(data).fadeIn('slow');
      $('#error-msg').delay(2000).fadeOut('slow');
    }
  });
});

The above solution gives me this

{
  "movies": [{
    "title": "fdfdfd",
    "movieurl": "http:\/\/meed.audiencevideo.com\/videos",
    "movieid": "1"
  }, {
    "title": "fdfdfd",
    "movieurl": "http:\/\/meed.audiencevideo.com\/videos",
    "movieid": "1"
  }]
}

I want movieid to increment dynamically eg movieid: 1, movieid: 2 etc. What do I need to do to get what I want?

Upvotes: 0

Views: 1342

Answers (3)

The Dead Man
The Dead Man

Reputation: 5566

Most of the solution provided by friends here are not well constructed, they don't give a perfect solution to my problem.

Most of the common problems were pointed out by @Randy Casburn

Here is my solution I found out working perfectly, I thought it will be good to share, maybe will help someone out there.

my json file looks like this

{
    "movies": [
        {
            "title": "sdsds",
            "movieurl": "https:\/\/meed.audiencevideo.com\/videos\/good_job.mp4",
            "movieid": 1,
            "buttons": []
        },
        {
            "title": "sdsds",
            "movieurl": "https:\/\/meed.audiencevideo.com\/videos\/do_you_want.mp4",
            "movieid": 2,
            "buttons": []
        },
  ]
}

Here is my js

function getNextMovieId() {
        var nextmovieid = 0;
        for (var a = 0; a < movies.length; a++) {
                if( movies[a].movieid>nextmovieid ) {
                        nextmovieid = movies[a].movieid;
                }
        }
        nextmovieid++;
        return nextmovieid;
}

  $("#btnAddMovie").click(function(e){

   var formData = $("#movieForm").serializeArray();
                             console.log(formData);
                             movies.push({
                                title: formData[0].value,
                                movieurl: formData[1].value,
                                movieid:  getNextMovieId(),
                                buttons: []
                            });

})

Upvotes: 0

Kavelin
Kavelin

Reputation: 444

You can put a parameter in the callback function. The parameters are (index, array), but you would only need index.

  $.each(formData, function(i) {
    console.log(formData);
    jsonData.push({
      title: formData[0].value,
      movieurl: formData[1].value,
      movieid: i + 1
    });
  });

Upvotes: 0

vatz88
vatz88

Reputation: 2452

From your code, you can use the index in the callback in the $.each

....
$.each(formData, function(index) {
   console.log(formData);
   jsonData.push({
      title: formData[0].value,
      movieurl: formData[1].value,
      movieid: index + 1
    });
  });
...

To understand the callback, see the jquery documentation https://api.jquery.com/jQuery.each/


Alternatively you can also use the jsonData.length

....
$.each(formData, function(index) {
   console.log(formData);
   jsonData.push({
      title: formData[0].value,
      movieurl: formData[1].value,
      movieid: jsonData.length + 1
    });
  });
...

Upvotes: 1

Related Questions