尝试在我的数组中放入 object 时,此过滤器函数不会删除旧的 object

When trying to PUT an object in my Array, this filter function is not removing the old object

回购: https://github.com/leongaban/api-design-node/tree/master

我的邮递员collection: https://www.getpostman.com/collections/b5a03b07836ad34b7758

预计:

当前 "lion" 个字符:

[
    {
        "id": "1",
        "name": "Teemo",
        "pride": "LoL",
        "age": "1",
        "gender": "male"
    },
    {
        "id": "2",
        "name": "Nasus",
        "pride": "LoL",
        "age": "10",
        "gender": "male"
    }
]

PUT http://localhost:3000/lions/1

正文:

{
    "age": "1",
    "gender": "female",
    "name": "LuLu",
    "pride": "LoL"
}

应该return GET 所有狮子的这个新列表:

[
    {
        "id": "1",
        "name": "LuLu",
        "pride": "LoL",
        "age": "1",
        "gender": "female"
    },
    {
        "id": "2",
        "name": "Nasus",
        "pride": "LoL",
        "age": "10",
        "gender": "male"
    }
]

结果

[
    {
        "id": "2",
        "name": "Nasus",
        "pride": "2",
        "age": "2",
        "gender": "female"
    },
    {
        "0": { // <-- This should not be here
            "id": "1",
            "name": "Teemo",
            "pride": "1",
            "age": "1",
            "gender": "female"
        },
        "age": "1",
        "gender": "female",
        "name": "LuLu",
        "pride": "LoL"
    }
]

完整 server.js

const express = require('express')
const app = express()
const bodyParser = require('body-parser')
const path = require('path')
const port = 3000

app.use(express.static('client'))
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())

let lions = []
let id = 0

app.get('/lions', function(req, res) {
  console.log('GET lions:', lions)
  res.json(lions)
})

app.get('/lions/:id', function(req, res) {
  let lion = lions.filter((lion => lion.id === req.params.id))

  res.json(lion || {})
})

app.post('/lions', function(req, res) {
  id++
  const lion = Object.assign({ id: id.toString() }, req.body)
  lions.push(lion)

  res.json(lion)
});

app.put('/lions/:id', function(req, res) {
  const paramId = req.params.id
  const updated = req.body

  if (updated.id) {
    delete updated.id
  }

  const oldLion = lions.filter((lion => lion.id === paramId))

  if (!oldLion) {
    res.send()
  }

  const newLion = Object.assign(updated, oldLion)
  console.log('newLion', newLion)
  lions = lions.filter(lion => lion.id !== paramId)
  lions.push(newLion)

  res.json(newLion)
});

app.listen(port, () => console.log(`NODE RUNNING on port: ${port}`))

PUT 函数

app.put('/lions/:id', function(req, res) {
  const paramId = req.params.id
  const updated = req.body

  if (updated.id) {
    delete updated.id
  }

  // Here I find the oldLion to replace by id:
  const oldLion = lions.filter((lion => lion.id === paramId))

  if (!oldLion) {
    res.send()
  }

  // Here I create a new object for the new "lion":
  const newLion = Object.assign(updated, oldLion)
  console.log('newLion', newLion)

  // Here I filter out the old lion:
  lions = lions.filter(lion => lion.id !== paramId)

  // New lion is pushed in:
  lions.push(newLion)

  res.json(newLion)
});

app.put() 方法可能存在的一个潜在问题是,当您执行 const oldLion = lions.filter((lion => lion.id === paramId)) 时,您将得到 array 作为结果。检查 Array.filter() for more info about this. So, I believe you want to use Array.find() 而不是 filter() 因为稍后您要调用:

const newLion = Object.assign(updated, oldLion);

而且,如果 oldLion 是一个 arraynumeric-properties 将被添加到 updated 对象,如下一个示例所示:

const updated = {somekey: "somevalue"};
console.log(Object.assign(updated, [{somekey: "updatedValue"}]));
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

因此,正如您所提到的,这会生成您意想不到的结构:

[
  {
    "id": "2",
    "name": "Nasus",
    "pride": "2",
    "age": "2",
    "gender": "female"
  },
  {
    "0": { // <-- This should not be here
        "id": "1",
        "name": "Teemo",
        "pride": "1",
        "age": "1",
        "gender": "female"
    },
    "age": "1",
    "gender": "female",
    "name": "LuLu",
    "pride": "LoL"
  }
]

更新

但是,在阅读了您评论的其他修复程序并了解了您正在尝试做的事情之后,也许最好使用 Array.findIndex() 并像这样编写您的 put() 方法:

app.put('/lions/:id', function(req, res)
{
    const paramId = req.params.id;
    const updated = req.body;

    if (updated.id)
        delete updated.id;

    // Here I find the oldLion to replace by id:
    const oldLionIdx = lions.findIndex(lion => lion.id === paramId);

    if (oldLionIdx < 0)
       res.send();

    // Here I update the object with the new "lion" properties:
    const newLion = Object.assign(lions[oldLionIdx], updated);
    console.log('newLion', newLion);

    res.json(newLion);
});