[英]How to just change object property values that exists?
我现在正在创建一个后端 API 并将所有数据存储在一个数组中,因为我还在学习。
我需要根据放置请求更新数组上的对象属性。 我只想替换客户端请求的数据,其余的必须保持不变。
我只知道如何对每个属性进行硬编码,例如 Arr.propertyA = req.body.propetyA...
我想知道是否有更好的方法来做到这一点。
为了清楚起见,这里是代码:
后端
const books = [
{
id: 1,
title: 'Book 1',
author: 'Author 1'
},
{
id: 2,
title: 'Book 2',
author: 'Author 2'
},
{
id: 3,
title: 'Book 3',
author: 'Author 3'
}
]
app.put('/api/books/:id', (req, res) => {
const foundIndex = books.findIndex(book => { return req.params.id == book.id });
books[foundIndex] = req.body;
res.send(books[foundIndex]);
}
前端
PUT:
url: http://localhost:5000/api/books/1
{
"title": "New Book 1",
"author": "New Author 1"
}
结果:
{
title: 'New Book 1',
author: 'New Author 1'
}
但我期待
{
id: 1,
title: 'New Book 1',
author: 'New Author 1'
}
============ 编辑 ==================
功能齐全,便于理解
app.put("/api/books/:id", (req, res) => {
const schema = {
title: Joi.string()
.min(3)
.required(),
author: Joi.string()
};
// Look up the course
const book = books.find(book => {
return req.params.id == book.id;
});
// If not existing, return 404
if (book.length === 0) {
res.status(404).send(`The book with ID: "${req.params.id}" was not found`);
return;
}
// Validate
const validation = Joi.validate(req.body, schema);
// If invalid, return 400 - Bad request
if (validation.error) {
res.status(400).send(validation.error.details[0].message);
return;
}
// Update the course
Object.assign(book, req.body);
// Return the updated course
res.send(book);
});
找到匹配的id
,使用Object.assign
将req.body
对象合并到书上。 (因为你并不真正关心找到的索引,只关心该索引处的书对象,最好使用.find
不是.findIndex
):
app.put('/api/books/:id', (req, res) => {
const book = books.find(book => { return req.params.id == book.id });
Object.assign(book, req.body);
res.send(book);
});
如果有可能没有与req.params.id
匹配的书,请确保在尝试使用它之前先检查book
存在。
如果,就像在你的例子中一样,一本书的id
总是匹配它在books
数组中的位置,使用括号表示法来访问正确的索引会更容易,而不是使用.find
:
app.put('/api/books/:id', (req, res) => {
const book = books[req.params.id];
Object.assign(book, req.body);
res.send(book);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.