【问题标题】:sum a number inside a map function and return the edited array of objects在 map 函数中求和一个数字并返回编辑后的对象数组
【发布时间】: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


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:
      (object.find((v)=>v.productId==='60709d8f24a9615d9cff2b77') || {}).quantity++;
      

      您可以使用此代码

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-10-18
        • 2013-08-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-09
        相关资源
        最近更新 更多