我有物件陣列list
,參數rid
和rorder
被傳遞。
-> 1. 如果rid
與清單中的id
相同,則用rorder
更新itemorder
> 值。
-> 2.UpdatedList uList
屬性itemorder
如果存在相同的值,則遞增該值,直到其連續順序(1,2, 3...n)
var rid = 23; var rvalue = 2 const list = [ { id: 12, itemorder:null, place : 'IN' }, { id: 24, itemorder: 1, place: 'MY' }, { id: 23, itemorder: 4, place: 'AU' }, { id: 44, itemorder: 3, place: 'SG' }, { id: 54, itemorder: 2, place: 'CN' }, ]; //updated List will be const uList = [ { id: 12, itemorder:null, place : 'IN' }, { id: 24, itemorder: 1, place: 'MY' }, { id: 23, itemorder: 2, place: 'AU' }, // updates since id and rid same // 2 { id: 44, itemorder: 3, place: 'SG' }, // 4 { id: 54, itemorder: 2, place: 'CN' }, // 3 ]; // uList property itemorder has same value here `2`, increment until consecutive (1,2, 3...n). Expected Output [ { id: 12, itemorder:null, place : 'IN' }, { id: 24, itemorder: 1, place: 'MY' }, { id: 23, itemorder: 2, place: 'AU' }, { id: 44, itemorder: 4, place: 'SG' }, { id: 54, itemorder: 3, place: 'CN' }, ];
Tried var listChanged = list.map(e=> ({ ...e, itemorder: e.id===rid ? rvalue : e.itemorder })) var result = listChanged.map(i => ({ ...e, itemorder: (i.itemorder !== rvalue && i.itemorder > rvalue) ? (i.itemorder || 0)+1 : i.itemorder }));
when passing var rid = 23; var rvalue = 1 Expected Output: [ { id: 12, itemorder:null, place : 'IN' }, { id: 24, itemorder: 2, place: 'MY' }, // 1 becomes 2 { id: 23, itemorder: 1, place: 'AU' }, // updates since both id and rid same { id: 44, itemorder: 4, place: 'SG' },//3 becomes 4 { id: 54, itemorder: 3, place: 'CN' }, //2 becomes 3 ] no repeat values so increment, follows consecutive order (1,2,3..n)
上面的程式碼應該可以工作。 到目前為止,根據我從您的問題中了解到的信息,我們執行以下步驟:
清單
中找出給定rid的項目列表
,並根據步驟1找到的索引,預設返回,如果項目索引與上面的索引匹配,則將iteorder返回為右值,並透過增加現有的iteorder來傳回如果項目索引大於找到的索引,則值加1