Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to remove property from object

We have an array of objects like this:

const arrOfObjects = [
  {
    name: 'Ronaldo',
    age: 20,
    status: true
  },
  {
    name: 'Messi',
    age: 30,
    status: false
  },
  {
    name: 'Benzema',
    age: 40,
    status: false
  },  
  {
    name: 'Vini',
    age: 50,
    status: false
  }
]

I would like to create new array of objects, based on this array, and add some new properties – so the map will be the best way.

const newArray = arrayOfObjects.map(obj => {
    return {
    ...obj,
    newProperty: 'newProperty',
    age:  // Here I want to check if status property is true, if yes, I would like to remove property age from current object
  }
})

I would like to remove age property from object, if status: true. How can I do it?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Extract the age with destructuring and use a conditional part to insert it again:

const arrOfObjects = [{name: 'Ronaldo',age: 20,status: true},{name: 'Messi',age: 30,status: false},{name: 'Benzema',age: 40,status: false},{name: 'Vini',age: 50,status: false}];

const newArray = arrOfObjects.map(obj => {
    let {age, ...rest} = obj;
    return {
        ...rest,
        newProperty: 'newProperty',
        ...!obj.status && {age} 
    }
});

console.log(newArray);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading