简体   繁体   English

不使用删除操作符从 JavaScript 对象中删除属性

[英]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 使用ES6解构运算符,您可以

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. 考虑您要删除id属性,以上代码将删除id属性并返回包含name属性的对象。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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