Home > Mobile >  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,
  })
})

CodePudding user response:

No need to initiate a new array because the map method returns a new array what you can do is map the array then delete the property or method that you want then return the new array. Here's a simple solution that you use for your reference

const filteredData = data.map(newData => {
    delete newData.status
    delete newData.check
    return newData
})

CodePudding user response:

Simply you can loop over array using forEach method and delete key, value pairs. For example data.forEach((obj) => { delete obj.status; delete obj.check; }) since array is a reference type you can easily mutate it and not create a duplicate of data.

  • Related