Reputation: 229
I want to find a property by ID, and if I find it I want to add + to the quantity property.
This is what I have tried but cant achieve to return the previous object with the new edited quantity.
any thoughts?
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')
In this case Id like to return:
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'
}
]
Upvotes: 0
Views: 877
Reputation: 6139
This function should give you exactly what you're looking for. The function finds the object, adds 1
to the quantity, and then returns the updated array of objects per your specifications.
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'));
Another possible case to consider here would be to return something else like false
if the object is not found rather than just returning the array of objects as is. You could even add a third parameter to support that option conditionally.
Upvotes: 1
Reputation: 875
(object.find((v)=>v.productId==='60709d8f24a9615d9cff2b77') || {}).quantity++;
You can use this code
Upvotes: 1