-1

I need remove object from array of objects in Javascript My code.

object

var prePlantio = [
    {
        "Dessecação": [
            { id:1,produto: 'Fortenza', dose: '60', area: '10' },
            { id:2,produto: 'Maxim', dose: '70', area: '10' },
        ]
    },
    {
        "TS": [
            { id:4,produto:'Fortenza', dose: '90', area: '10' },
            { id:5,produto:'Maxim', dose: '100', area: '10' },
        ]
    }
]

I would like to remove "Dessecação" -> id = 2 my code to try remove.

var removeItem = function(where = 'prePlantio',product = 2){
    let etapa = eval(where);
    var index = Object.values(etapa[0]).map(function(item) { 
        return item.id;
    }).indexOf(product);
    Object.values(etapa[0]).splice(index, 1);
}
removeItem()

JSFiddle

Herick
  • 217
  • 3
  • 10
  • Does this answer your question? [How can I remove a specific item from an array?](https://stackoverflow.com/questions/5767325/how-can-i-remove-a-specific-item-from-an-array) – Mister Jojo Mar 25 '20 at 23:16
  • 4
    I think your main issue is that the array returned by `Object.values` is a new array, not a reference to the source data – Phil Mar 25 '20 at 23:19

2 Answers2

1

var prePlantio = [{
    "Dessecação": [{
        id: 1,
        produto: 'Fortenza',
        dose: '60',
        area: '10'
      },
      {
        id: 2,
        produto: 'Maxim',
        dose: '70',
        area: '10'
      }
    ]
  },
  {
    "TS": [{
        id: 4,
        produto: 'Fortenza',
        dose: '90',
        area: '10'
      },
      {
        id: 5,
        produto: 'Maxim',
        dose: '100',
        area: '10'
      },
    ]
  }
]

function removeItem(obj, id) {
   let updatedObj = obj.map((x, i) => {
    let objKeys = Object.keys(x);
    let eles = obj[i][objKeys].filter((o) => o.id !== id)
     obj[i][objKeys]=eles;
     return obj[i];
     
  })
  return updatedObj;
}
let updatedObj = removeItem(prePlantio, 2);
console.log(updatedObj);

We iterate through the array provided as input parameter to removeItem and then, find the keys of it, loop through the keys and filter out the requested id (which is a parameter for remove Item). Hope this helps!

0

maybe that...?

const prePlantio = 
  [ { "Dessecação": 
      [ { id: 1, produto: 'Fortenza', dose: '60', area: '10' } 
      , { id: 2, produto: 'Maxim',    dose: '70', area: '10' } 
    ] } 
  , { "TS": 
      [ { id: 4, produto: 'Fortenza', dose: '90',  area: '10' } 
      , { id: 5, produto: 'Maxim',    dose: '100', area: '10' } 
  ] } ] 
  ;
const removeItem = ( arr, subID) =>
  {
  for (elm of arr)
    {
    let subArr = elm[ Object.keys(elm)[0] ] 
      , indx   = subArr.findIndex(sElm=>sElm.id===subID)
      ;
    if (indx>=0)
      {
      subArr.splice(indx, 1);
      break
      }
    }
  }

removeItem(prePlantio, 2)

console.log ( prePlantio )
.as-console-wrapper { max-height: 100% !important }
Mister Jojo
  • 12,060
  • 3
  • 14
  • 33