如何在对象数组中动态添加id属性?

时间:2019-08-19 14:25:34

标签: javascript jquery arrays

我有一个简单的部分,用户可以在其中使用表单添加电影详细信息。我正在接受用户输入的值,并根据它们创建一个对象,然后将其推入数组。但是,我还想为每部添加的电影添加一个动态ID。

$("#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');
    }
  });
});

上述解决方案给了我

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

我希望movieid动态增加,例如movieid: 1movieid: 2等。要获得我想要的东西,我需要做些什么?

4 个答案:

答案 0 :(得分:1)

通过代码,您可以在$.each

的回调中使用索引
....
$.each(formData, function(index) {
   console.log(formData);
   jsonData.push({
      title: formData[0].value,
      movieurl: formData[1].value,
      movieid: index + 1
    });
  });
...

要了解回调,请参阅jquery文档https://api.jquery.com/jQuery.each/


或者,您也可以使用jsonData.length

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

答案 1 :(得分:0)

尝试一下:

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


    });

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


    });

这些只是简单的示例,仅当您不打算从数组中删除项目时才可以使用。

答案 2 :(得分:0)

您可以在回调函数中放置一个参数。参数是(索引,数组),但是您只需要索引。

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

答案 3 :(得分:0)

这里的朋友提供的大多数解决方案的结构都不完善,无法为我的问题提供完美的解决方案。

@Randy Casburn指出了大多数常见问题

这是我发现可以完美工作的解决方案,我认为分享会很好,也许会帮助某个人。

我的json文件看起来像这样

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: []
                            });

})

这是我的js

java.lang.IllegalArgumentException: Unable to locate adb
    at com.android.tools.idea.run.editor.DeployTargetPickerDialog.<init>(DeployTargetPickerDialog.java:144)
    at com.android.tools.idea.run.editor.ShowChooserTargetProvider.showPrompt(ShowChooserTargetProvider.java:113)
    at com.android.tools.idea.run.AndroidRunConfigurationBase.getDeployTarget(AndroidRunConfigurationBase.java:600)
    at com.android.tools.idea.run.AndroidRunConfigurationBase.doGetState(AndroidRunConfigurationBase.java:281)
    at com.android.tools.idea.run.AndroidRunConfigurationBase.getState(AndroidRunConfigurationBase.java:241)
    at com.intellij.execution.runners.ExecutionEnvironment.getState(ExecutionEnvironment.java:158)
    at com.intellij.execution.runners.BaseProgramRunner.execute(BaseProgramRunner.java:55)
    at com.intellij.execution.runners.BaseProgramRunner.execute(BaseProgramRunner.java:50)
    at com.intellij.execution.ProgramRunnerUtil.executeConfigurationAsync(ProgramRunnerUtil.java:92)
    at com.intellij.execution.ProgramRunnerUtil.executeConfiguration(ProgramRunnerUtil.java:41)
    at com.intellij.execution.impl.ExecutionManagerImpl.restart(ExecutionManagerImpl.java:93)
    at com.intellij.execution.impl.ExecutionManagerImpl.access$300(ExecutionManagerImpl.java:44)
    at com.intellij.execution.impl.ExecutionManagerImpl$3.run(ExecutionManagerImpl.java:442)
    at com.intellij.util.concurrency.QueueProcessor.runSafely(QueueProcessor.java:232)
    at com.intellij.util.Alarm$Request.runSafely(Alarm.java:356)
    at com.intellij.util.Alarm$Request.run(Alarm.java:343)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at com.intellij.util.concurrency.SchedulingWrapper$MyScheduledFutureTask.run(SchedulingWrapper.java:228)
    at com.intellij.openapi.application.TransactionGuardImpl$2.run(TransactionGuardImpl.java:315)
    at com.intellij.openapi.application.impl.LaterInvocator$FlushQueue.doRun(LaterInvocator.java:435)
    at com.intellij.openapi.application.impl.LaterInvocator$FlushQueue.runNextEvent(LaterInvocator.java:419)
    at com.intellij.openapi.application.impl.LaterInvocator$FlushQueue.run(LaterInvocator.java:403)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:762)
    at java.awt.EventQueue.access$500(EventQueue.java:98)
    at java.awt.EventQueue$3.run(EventQueue.java:715)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:732)
    at com.intellij.ide.IdeEventQueue.defaultDispatchEvent(IdeEventQueue.java:755)
    at com.intellij.ide.IdeEventQueue._dispatchEvent(IdeEventQueue.java:704)
    at com.intellij.ide.IdeEventQueue.dispatchEvent(IdeEventQueue.java:391)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)