簡體   English   中英

合並對象並刪除屬性

[英]Combine object and delete a property

假設我有一個這樣結構的對象數組

"err": [
    {
        "chk" : true,
        "name": "test"
    },
    {
        "chk" :true
        "post": "test"
    }
]

我怎樣才能像這樣重新構建它:

"err": [
    {
        "post": "test"
        "name": "test"
    }
]

我試過

arr.filter(obj => delete obj.chk);

它可以成功刪除chk屬性,但是如何合並兩個對象?

您可以將它們展開到Object.assign以創建一個新對象,然后從該對象中刪除chk屬性:

 const err = [ { "chk" : true, "name": "test" }, { "chk" :true, "post": "test" } ]; const newObj = Object.assign({}, ...err); delete newObj.chk; console.log([newObj]);

另一種不刪除的方法是在左側解構chk ,並使用 rest 語法:

 const err = [ { "chk" : true, "name": "test" }, { "chk" :true, "post": "test" } ]; const { chk: _, ...newObj } = Object.assign({}, ...err); console.log([newObj]);

暫無
暫無

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

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