从数组Javascript中删除多个对象

数码相机

我正在尝试从嵌套在对象中的详细信息数组下面的_id“ bennyRawMaterial”删除所有对象:

let recipeBasicRecipes = [{
_id:'12345',
name:'Macaron Shell',
details:[
  {
    name: 'Sugar',
    _id: 'bennyRawMaterial',
    type: 'solid',
  }
,  
  {  
    name: 'Egg white',
    _id: '5fef680ca43301322a3224e5',
    type: 'solid'
  }]
},
{
_id:'14512345',
name:'Macaron Shell',
details:[{  
    name: 'Castiors gar',
    _id: 'bennyRawMaterial',
    type: 'solid'
  },
  {
    name: 'oil',
    _id: 'bennyRawMaterial',
    type: 'solid',
  }
,  {
    name: 'food',
    _id: 'bennyRawMaterial',
    type: 'solid',

  }]
}]

我正在使用以下代码删除对象,但是跳过了一些对象。请帮助实现

recipeBasicRecipes.forEach(br => {
        br.details.forEach((rm, index) => {
          if (rm._id === 'bennyRawMaterial') {
            br.details.splice(index, 1);
          } else {
            return true;
          }
        });

阿扎德
  • 维护一个全局id数组,
  • 并遍历每个对象的详细信息数组
  • 检查ID是否存在于全局ID数组中

let recipeBasicRecipes = [{
    _id: '12345',
    name: 'Macaron Shell',
    details: [{
        name: 'Sugar',
        _id: 'bennyRawMaterial',
        type: 'solid',
      },
      {
        name: 'Egg white',
        _id: '5fef680ca43301322a3224e5',
        type: 'solid'
      }
    ]
  },
  {
    _id: '14512345',
    name: 'Macaron Shell',
    details: [{
        name: 'Castiors gar',
        _id: 'bennyRawMaterial',
        type: 'solid'
      },
      {
        name: 'oil',
        _id: 'bennyRawMaterial',
        type: 'solid',
      }, {
        name: 'food',
        _id: 'bennyRawMaterial',
        type: 'solid',

      }
    ]
  }
]


var uniqueIds = []; //global ids array
recipeBasicRecipes.forEach(el => { 

  
  let details = [];//unique details array
  el.details.forEach((dt, i) => {

    let id = dt._id;
    if (!uniqueIds.includes(id)){ //check id exists in global ids array
      uniqueIds.push(id);
      details.push(dt); //copy unique details
    }
  });

  el.details = details; //update details with unique details
});

console.log(recipeBasicRecipes)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章