简体   繁体   中英

How to insert an array to a node js web service through angular js?

I am trying to insert an array of data to a node js web service. The code looks like this.

$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;
        }
      }

If I print the selectedMap in console, I am getting array like this.

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

But I need to get like this to insert into DB

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

can anybody please help me to do this..?

You are adding key value in array instead of adding object.

Based on your output, selectedMap is not defined properly. It should be selectedMap = []; instead of selectedMap = {}; wherever you defined in your code.

Try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM