首页 > 解决方案 > 在 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'
}
]

标签: javascriptarraysarray.prototype.map

解决方案


这个功能应该给你你正在寻找的东西。该函数找到对象,添加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如果找不到对象,则返回其他内容,而不是按原样返回对象数组。您甚至可以添加第三个参数来有条件地支持该选项。


推荐阅读