javascript - 在 map 函数中求和一个数字并返回编辑后的对象数组
问题描述
我想按 ID 查找属性,如果找到,我想将 + 添加到数量属性。
这是我尝试过但无法使用新编辑的数量返回前一个对象的方法。
有什么想法吗?
const object = [
{
_id: '6078db5aa82f5c34409d53f4',
productId: '60709d8f24a9615d9cff2b75',
quantity: 1,
createdAt: '2021-04-16T00:33:46.816Z',
updatedAt: '2021-04-16T00:33:46.816Z'
},
{
_id: '6078db5aa82f5c34409d53f4',
productId: '60709d8f24a9615d9cff2b76',
quantity: 1,
createdAt: '2021-04-16T00:33:46.816Z',
updatedAt: '2021-04-16T00:33:46.816Z'
},
{
_id: '6078db5aa82f5c34409d53f4',
productId: '60709d8f24a9615d9cff2b77',
quantity: 1,
createdAt: '2021-04-16T00:33:46.816Z',
updatedAt: '2021-04-16T00:33:46.816Z'
}
]
function findID(arr, val ){
return arr.map(function(arrVal){
if( val === arrVal.productId){
return [...arr, {arrVal.quantity +1 }]
}
})
}
findID(object, '60709d8f24a9615d9cff2b77')
在这种情况下,我想返回:
const object = [
{
_id: '6078db5aa82f5c34409d53f4',
productId: '60709d8f24a9615d9cff2b75',
quantity: 1,
createdAt: '2021-04-16T00:33:46.816Z',
updatedAt: '2021-04-16T00:33:46.816Z'
},
{
_id: '6078db5aa82f5c34409d53f4',
productId: '60709d8f24a9615d9cff2b76',
quantity: 1,
createdAt: '2021-04-16T00:33:46.816Z',
updatedAt: '2021-04-16T00:33:46.816Z'
},
{
_id: '6078db5aa82f5c34409d53f4',
productId: '60709d8f24a9615d9cff2b77',
quantity: 2,
createdAt: '2021-04-16T00:33:46.816Z',
updatedAt: '2021-04-16T00:33:46.816Z'
}
]
解决方案
这个功能应该给你你正在寻找的东西。该函数找到对象,添加1
数量,然后根据您的规范返回更新的对象数组。
const object = [{
_id: '6078db5aa82f5c34409d53f4',
productId: '60709d8f24a9615d9cff2b75',
quantity: 1,
createdAt: '2021-04-16T00:33:46.816Z',
updatedAt: '2021-04-16T00:33:46.816Z'
},
{
_id: '6078db5aa82f5c34409d53f4',
productId: '60709d8f24a9615d9cff2b76',
quantity: 1,
createdAt: '2021-04-16T00:33:46.816Z',
updatedAt: '2021-04-16T00:33:46.816Z'
},
{
_id: '6078db5aa82f5c34409d53f4',
productId: '60709d8f24a9615d9cff2b77',
quantity: 1,
createdAt: '2021-04-16T00:33:46.816Z',
updatedAt: '2021-04-16T00:33:46.816Z'
}
];
const findID = (arr, id) => (arr.find(product => product.productId === id && ++product.quantity), arr);
console.log(findID(object, '60709d8f24a9615d9cff2b77'));
这里要考虑的另一种可能的情况是false
如果找不到对象,则返回其他内容,而不是按原样返回对象数组。您甚至可以添加第三个参数来有条件地支持该选项。
推荐阅读
- javascript - 如何选择屏幕上给定y之间的所有元素
- ocaml - 代入 Z3 表达式中的操作
- javascript - 反应卡内的自定义下拉菜单
- jenkins - Jenkins 的 TFS 插件是否已删除?
- laravel - Laravel 不同的是不能使用 where() 和 paginate
- python - 有没有比在 python 中使用 loc 更快的方法来根据现有数据框填充数据框中的新列?
- c - 如何将 qsort 用于结构成员?
- javascript - 如何在每次鼠标按下时为按钮添加样式?
- android - Android Kotlin - 分类器“Activity”没有伴随对象,因此必须在此处初始化
- reveal.js - Reveal.js 如何在动画中使用浮动图像