javascript - 无法根据 id 更改项目,预期结果应该是输出格式,它应该返回正确的值和更新的值
问题描述
无法根据 id 更改项目,预期结果应为输出格式
const items = [
{ id: 1, value: "first" },
{ id: 2, value: "second" },
{ id: 3, value: "third" }
];
const expectedOutput = [
{ id: 1, value: "first" },
{ id: 2, value: "newvalue" },
{ id: 3, value: "third" }
]
function getData(value, id) {
return items.map((_each)=> {
if(_each.id === id) {
//need to update items with id=2
}
})
}
console.log(getData("newvalue", 2))
解决方案
const items = [
{ id: 1, value: "first" },
{ id: 2, value: "second" },
{ id: 3, value: "third" }
];
const expectedOutput = [
{ id: 1, value: "first" },
{ id: 2, value: "newvalue" },
{ id: 3, value: "third" }
]
function getData(value, id) {
return items.map((each)=> {
if(each.id === id) {
//need to update items with id=2
return {...each, value}
}else{
return each }
})
}
console.log(getData("newvalue", 2))
推荐阅读
- discord.py - 试图让 Discord 机器人发送使用多个随机选择的单词的消息
- c++ - 当文件夹包含空格时 wordexp_t 失败
- excel - 如何使用集合和地图功能更好地导出 Laravel 项目
- javascript - 如何在javascript中使用ffmpeg设置输出视频的帧率
- git - git合并:“错误:无法统计'文件':权限被拒绝”
- java - java中N数组-树结构的实现
- r - 在 R 中,访问存储在 SP 中的 Excel 文件实际上获取的是 HTML 引用,而不是实际文件
- django - 过滤器集字段不适用于多个对象
- powershell - 将 UFormat 应用于 System.DateTime 变量
- api - IBM Cloud:使用哪个 API 来获取所有已批准的块卷的列表