简体   繁体   中英

Delete a property from JavaScript object without using delete operator

I need to extract certain properties from an object and assign to a new object. In a traditional way, I can assign manually whats required from an object property to a new object's property.

Currently i am using delete operator on the original object and creating a new object.

Is there a better way to do it.

You could destructure an object and pick the unwanted and get the rest as result object.

It uses

 var object = { a: 1, b: 2, c: 3 }, key = 'a', { [key]:_, ...result } = object; console.log(result); 

Using ES6 Deconstructing Operator you can do a

ler arr = [{id:1, name: foo}, {id:2, name: bar}]
arr.map({id, ...item} => {
   return item
})

Consider you want to remove id property the above code will remove the id property and returns the object containing the name property.

You have to create new object by copying all the properties from the old, except the one you want to remove:

 const person = {
      name: 'abc',
      age: 25
    };

    console.log(person);

    const age = 'age';

    const newPerson = Object.keys(person).reduce((object, key) => {
      if (key !== age) {
        object[key] = person[key]
      }
      return object
    }, {});

    console.log(newPerson);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM