如何使用GET

时间:2019-05-17 09:26:16

标签: javascript arrays node.js get array-splice

下面的代码应该使用GET从JSON文件中的数组中删除某些内容。但是,无论输入什么数字,它都只会转到显示错误消息的else语句。我似乎无法理解我在做什么错,因为控制台中也未显示任何错误。

此代码的目的是从数组中删除与JSON文件中元素ID相同的元素。因此,如果get请求为delete/02,则应删除数组中ID为02的元素,而不是数组中的第三个元素。

var fs = require('fs');
var rawData = fs.readFileSync('toDoList.json');
var tasksArray = JSON.parse(rawData);
console.log(list);



app.get('/delete/:id', function (req, res) {

	for (var i = 0; i < tasksArray.length; i++) {

			if(tasksArray[i]["id"] == req.params['id']) {

				tasksArray.splice([i], 1);

				var json = JSON.stringify(tasksArray);
				fs.writeFileSync("toDoList.json", json, "utf8");
				res.json(tasksArray);

				console.log[i];

	 		}

	 		else {
				res = res.status(500);
				res.json({"status": "error"});
			}

		break;

	}

});

如果有帮助,请参见JSON:

[
  {
    "id": "01",
    "desc": "Assignment 1"
  },
  {
    "id": "02",
    "desc": "Assignment 2"
  },
  {
    "id": "03",
    "desc": "Assignment 3"
  },
  {
    "id": "04",
    "desc": "Assignment 4"
  },
  {
    "id": "05",
    "desc": "Assignment 5"
  }
]

1 个答案:

答案 0 :(得分:0)

我希望使用基本过滤器

var tasksArray = [
  {
    "id": "01",
    "desc": "Assignment 1"
  },
  {
    "id": "02",
    "desc": "Assignment 2"
  },
  {
    "id": "03",
    "desc": "Assignment 3"
  },
  {
    "id": "04",
    "desc": "Assignment 4"
  },
  {
    "id": "05",
    "desc": "Assignment 5"
  }
];

var id_to_delete = "02";

var remainingTasks = tasksArray.filter( task => task.id !== id_to_delete );

// write remainingTasks back into the JSON file as before.
console.log( remainingTasks );

根据评论.splice( i, 1 );也应该起作用。

PS:我希望id是实际数字而不是字符串。这将有助于排序,您不必在添加项目时检查是否需要在前面加上0,只需当前长度+ 1等于下一个ID。

//var fs = require('fs');
//var rawData = fs.readFileSync('toDoList.json');
//var tasksArray = JSON.parse(rawData);
var tasksArray = [
  { "id": "01", "task": "do 1" },
  { "id": "02", "task": "do 2" },
  { "id": "03", "task": "do 3" },
  { "id": "04", "task": "do 4" },
  { "id": "05", "task": "do 5" }
];

console.log( tasksArray );

//app.get('/delete/:id', function (req, res) {

  //var id_to_delete = req.params.id;
  var id_to_delete = "02";
  
  var remainingTasks = tasksArray.filter( task => {
    if ( task.id === id_to_delete ) {
      console.log( 'filtering away task with id: ' + task.id );
      console.log( task );
      return false;
    }
    else return true;
  });
  // Doublecheck that exactly one item was removed.
  if ( remainingTasks.length === tasksArray.length - 1 ) {
    var json = JSON.stringify( remainingTasks );
    // fs.writeFileSync("toDoList.json", json, "utf8");
    // res.json( remainingTasks );
    console.log( json );
  }
  else {
    //res = res.status(500);
	  //res.json({"status": "error"});
    console.log( 'error' );
  }

// });