我正在尝试将数据数组插入到节点js Web服务。代码看起来像这样。

$scope.addList = function(task,subtask){
         subtask.checked= !(subtask.checked);
       var data = {
       "taskId": task._id,
       "subTaskName": subtask.subTaskName,
     };
        if(subtask.checked){

          angular.forEach(data, function(value,key){
            this.push(key + ': ' + value);
          },selectedMap);

        }
        else{
          delete selectedMap;
        }
      }


如果我在控制台中打印selectedMap,我将得到这样的数组。

tasks:  {
0: "taskId: 1"
1: "subTaskName: SOW Updation"
2: "taskId: 1"
3: "subTaskName: Estimation - High Level"
4: "taskId: 2"
5: "subTaskName: Feasibility Study"
}


但是我需要像这样插入数据库

subTasks: [{
"task_id": 1,
"subTaskName": "Requirements Analysis"
},
{
"subTaskName": "Feasibility Study",
"task_id": 2
},
{
"subTaskName": "Requirement Elicitation",
"task_id": 3
},
{
"subTaskName": "Requirements Understanding",
"task_id": 4
},
{
"subTaskName": "Requirement Documentation",
"task_id": 5
}]


有人可以帮我做到这一点吗?

最佳答案

您在数组中添加键值,而不是添加对象。

根据您的输出,selectedMap的定义不正确。它应该是
在代码中的任何地方定义selectedMap = [];代替selectedMap = {};

尝试这个:

$scope.addList = function(task,subtask){
  subtask.checked= !(subtask.checked);
  var data = {
    "task_id": task._id,  // Updated key name based on your required output
    "subTaskName": subtask.subTaskName,
  };
  if(subtask.checked){
    selectedMap.push(data); // Add data object in array instead of key value pair
  } else {
    selectedMap = selectedMap.filter(function(obj) {
          return (obj.task_id !== data.task_id && obj.subTaskName !== data.subTaskName);
    });
}

10-06 05:28