简体   繁体   中英

How can i remove a field from an object

I have an array of object. For doing one opetation I need to remove few fields from this object and for some other operation I have to use the whole fields

But both of the array removing "regex" field. What is the mistake I am doing here?

 var newob = {}; var myObject = { "ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*" }; newob = JSON.stringify(myObject); delete newob.regex; console.log("Test1", newob); console.log("Test2", myObject);

You're missing JSON.parse so you can create the object back. Otherwise, you're trying to delete a property regex of a string , which doesn't exist.

newob = JSON.parse(JSON.stringify(myObject));

JSON.stringify creates a string, you need to do JSON.parse to create an object from a JSON string.

For that object, you can use Object.assign({}, myObject) since it's a shallow clone.

newob = Object.assign({}, myObject);
// newobj = { ...myObject } // this will also work

The problem is that newObj is not a copy of myObject but a reference to it. Thus when you delete the filed of myObject you also see the change in newObj

To explain what I have said, look at this snippet:

> const a = {a: 1}
undefined
> b = a
{ a: 1 }
> a.c = 58
58
> b
{ a: 1, c: 58 }

You can copy the object like this:

const newobj = JSON.parse(JSON.stringify(myObject));

then changes on myObject won't affect newobj

There is an other problem:

newob = JSON.stringify(myObject); 

is wrong here because you assign you want an object but JSON.stringify returns a string

If I understand you correctly you want to map the input data and remove the regex from each of the objects in your input array.

const items = [
    {
        ircEvent: 'PRIVMSG',
        method: 'newURI',
        regex: '^http://.*',
    },
    {
        ircEvent: 'TEST',
        method: 'newURI',
        regex: '^http://.*',
    },
]

const newItems = items.map(({ regex, ...item }) => item)

A good way to explain what is happening above is

const newArray = array.map(({dropAttr1, ...keepAttrs}) => keepAttrs)

But should you want to remove the key from one object only you could

const myObject = {
    ircEvent: 'PRIVMSG',
    method: 'newURI',
    regex: '^http://.*',
}

const { regex, ...noRegex } = myObject

console.log(noRegex)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

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