0

I have an array object below. I want to remove secondItem and fourthItem. I tried doing this but no luck

    var removed = item.splice(1)

How can I remove secondItem and fourthItem at the same time?

    items:[]

    0:
      firstItem: "testing"
      secondItem: "record"
      thirdItem: 30
      fourthItem: "40"
    1:
      firstItem: "testing2"
      secondItem: "record2"
      thirdItem: 33
      fourthItem: 44

It should look like this after removal 0: firstItem: "testing"
thirdItem: 30 1: firstItem: "testing2" thirdItem: 33

Baba
  • 2,059
  • 8
  • 48
  • 81
  • 1
    It is not clear what your object structure is. Could you please use valid JavaScript literals? Also add the structure as it should be after the removal. – trincot Feb 07 '19 at 21:31
  • Is it json? What is it? – basic Feb 07 '19 at 21:32
  • You can't remove them at the same time. Arrays don't work that way. Also it looks like you have an array of objects but actually you're trying to remove properties from the objects, rather than trying to remove objects from the array. Splice is the wrong tool for that. Splice removes items from an array. So you could remove first or second object from the array but it won't affect the properties of the objects themselves. – geoidesic Feb 07 '19 at 21:34

2 Answers2

0

In this case for the object you have stored at the array, won't work splice method, if you want to delete the second and fourth items in your objects use delete:

items.forEach(item => { 
  delete item.secondItem;
  delete item.fourthItem;  
});
Jose Rojas
  • 3,490
  • 3
  • 26
  • 40
0

const values = [

  {
    firstItem: "testing",
    secondItem: "record",
    thirdItem: 30,
    fourthItem: "40"
  }, {
    firstItem: "testing2",
    secondItem: "record2",
    thirdItem: 33,
    fourthItem: 44
  }
]


const res = values.map(({
  firstItem,
  thirdItem
}) => ({
  firstItem,
  thirdItem
}))

console.log(res)
Aziz.G
  • 3,599
  • 2
  • 17
  • 35