簡體   English   中英

如何在對象的屬性上添加屬性?

[英]How do I add a property on a property of an object?

我在 redux 狀態下使用 normalizer,我必須為 UI 指示器添加一個加載對象,

因此,如果我們假設這是我的規范化對象:

const myState  = {
   obj1: {
    a:1,
    b:2
   },
   obj2: {
    a:2,
    b:3
   }
}

這就是我想要做的,在 obj1 和 obj2 屬性上:我想動態添加這個對象:

loading:{ update_a: false }

我該怎么做? 我不知道如何操作Axios響應上的數組; 我是在減速機上做的。

我們可以這樣做:

Object.keys(myState).reduce((acc, key) => {acc[key] = {...myState[key],loading:{ update_a: false } }; return acc;},{})

我們將分離現有狀態並使用我們想要的添加屬性構建一個新版本:

Object.fromEntries(
  Object.entries(myState)
    .map(([key, obj]) => [
      key, 
      { 
        ...obj, // copy properties from the existing obj
        loading: { // and add the loading property
          update_a: false 
        }
      }
    ])
); 

希望比我在評論中的單行版本更容易閱讀。

你可以使用Object.entries做類似的事情並reduce

 const myState = { obj1: { a: 1, b: 2 }, obj2: { a: 2, b: 3 } } const res = Object.entries(myState).reduce((all, [key, value]) => { all[key] = { ...value, loading: { updated_a: false } } return all; }, {}) console.log(res)

暫無
暫無

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

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