【发布时间】:2021-07-11 06:30:17
【问题描述】:
我想通过 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'
}
]
【问题讨论】:
标签: javascript arrays array.prototype.map