簡體   English   中英

如何從 object 中刪除字段

[英]How can i remove a field from an object

我有一個 object 數組。 為了進行一項操作,我需要從此 object 中刪除幾個字段,而對於其他一些操作,我必須使用整個字段

但是這兩個數組都刪除了“正則表達式”字段。 我在這里做錯了什么?

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

您缺少JSON.parse因此您可以創建 object 回來。 否則,您將嘗試delete不存在的string的屬性regex

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

JSON.stringify創建一個字符串,您需要執行JSON.parse從 Z0ECD111C1D7A2D87A20 字符串創建一個 object。

對於 object,您可以使用Object.assign({}, myObject)因為它是一個淺克隆。

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

問題是newObj不是myObject的副本,而是對它的引用。 因此,當您刪除myObject的字段時,您還會看到newObj的變化

為了解釋我所說的,請看這個片段:

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

您可以像這樣復制 object:

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

那么myObject上的更改不會影響newobj

還有一個問題:

newob = JSON.stringify(myObject); 

在這里是錯誤的,因為你指定你想要一個 object 但 JSON.stringify 返回一個字符串

如果我理解正確,您希望 map 輸入數據並從輸入數組中的每個對象中刪除regex

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

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

解釋上面發生的事情的一個好方法是

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

但是如果您想從一個 object 中刪除密鑰,只有您可以

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM