0

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

1
  • The map method expects that you return a new value for each item in the array. So in your case, return an object with the two properties your want. Commented Oct 1, 2022 at 8:25

4 Answers 4

2

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
               }
    })
Sign up to request clarification or add additional context in comments.

1 Comment

"Instead of pushing to another" ... map does create a new array, too.
0

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

Comments

0

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
})

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.