![](/img/trans.png)
[英]Immutable change array of object inside array of objects state in reactjs
[英]Object updation inside loop with immutable state
我正在研究React應用程序,我需要更新我的objcet內部循環,我的對象結構是,
[{
"iD": "101",
"bD": "06/02/2018",
"cD": "16/04/2018"
},
{
"iD": "102",
"bD": "06/02/2018",
"cD": "16/04/2018"
},
{
"iD": "103",
"bD": "06/02/2018",
"cD": "16/04/2018"
}]
我的想法是我必須為每個對象添加幾個鍵,我采取的方法似乎不合適,因為我正在更新對象但沒有在數組中推送更新的值並返回新值。 有沒有其他方法可以用突變更新它?
我正在嘗試循環:
let newList = {};
for (let key in list) {
newList = Object.assign({}, list[key]);
newList.newKey1 = 'demo1';
newList.newKey2 = 'demo2';
};
現在,如果我返回newList,它將始終具有最后更新的值。 那么我將如何獲得完整的更新列表。 數組可能只有一個項目,如:
[{
"id":"101",
"bD":"06/02/2018",
"cD":"16/04/2018"
}]
要通過直接變異將數組中的每個項目轉換為其他項目,您只需使用for( for..of
或forEach
)循環的版本:
const items = [{ iD: "101", bD: "06/02/2018", cD: "16/04/2018" }, { iD: "102", bD: "06/02/2018", cD: "16/04/2018" }, { iD: "103", bD: "06/02/2018", cD: "16/04/2018" } ]; for (const item of items) { item.newKey1 = 'demo1'; item.newKey2 = 'demo2'; } console.log( items );
要通過返回更改了項目的新數組將數組中的每個項目轉換為某個項目,您應該使用Array.prototype.map
:
const items = [ { iD: "101", bD: "06/02/2018", cD: "16/04/2018" }, { iD: "102", bD: "06/02/2018", cD: "16/04/2018" }, { iD: "103", bD: "06/02/2018", cD: "16/04/2018" } ]; console.log( items.map(item => Object.assign({}, item, { newKey1: "demo1", newKey2: "demo2" }) ) );
或者,如果您的環境支持,則使用對象傳播:
const items = [ { iD: "101", bD: "06/02/2018", cD: "16/04/2018" }, { iD: "102", bD: "06/02/2018", cD: "16/04/2018" }, { iD: "103", bD: "06/02/2018", cD: "16/04/2018" } ]; console.log( items.map(item => ({ ...item, newKey1: "demo1", newKey2: "demo2" })) );
我解決了這個有一個數組並且每次都更新了obj。
當然,
const items = [
{
iD: "101",
bD: "06/02/2018",
cD: "16/04/2018"
},
{
iD: "102",
bD: "06/02/2018",
cD: "16/04/2018"
},
{
iD: "103",
bD: "06/02/2018",
cD: "16/04/2018"
}
];
let bObj = {};
let uObj = [];
for ( const item of items ) {
bObj = Object.assign({}, item )
bObj.newKey1 = 'Test1';
bObj.newKey2 = 'Test2';
uObj.push(bObj);
}
return uObj;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.