Home > Back-end >  how to remove key values in array of objects
how to remove key values in array of objects

Time:10-01

I am having a array of objects which looks like this

var data = [
    {
        "id": "K014-s1",
        "status": true,
        "amount": 992,
        "check": true,
      
    },
    {
        "id": "K014-s2",
        "status": false,
        "amount": 10992,
        "check": true,
       
    }
]

I want only certain key values from the object in the array

Required Output:

 var data = [
        {
            "id": "K014-s1",
            "amount": 992,
        },
        {
            "id": "K014-s2",
            "amount": 10992,
        }
    ]

Code I tried:

     var filteredData = []
        var result = data.map((obj) => {
        filteredData.push(obj.id)
        })

console.log(filteredData)

I tried. But don't Know how to make it. Please Help me with some solutions

CodePudding user response:

instead of pushing object to another array,you can simply map your data like this

    var result = data.map((obj) => {
        return {
                id:obj.id,
                amount:obj.amount
               }
    })

CodePudding user response:

Array.prototype.map already creates a new array, so result will already be the new value you are looking for.

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

var filteredResult = data.map((obj) => {
   //additional logic, if needed here.
   return {
      id: obj.id,
      amount: ob.amount,
   }        
})

Alternatively you can of course use a for loop or array.prototype.forEach to achieve the same:

var filteredData = []
data.forEach((obj) => {
  filteredData.push({
    id: obj.id,
    amount: ob.amount,
  })
})
  • Related