我有对象数组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)
P粉8659009942024-04-05 11:53:36
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' }, ]; let ridIdx = list.findIndex(x => x.id === rid) orderedList = list.map((l,i) => { if(i === ridIdx) { return { ...l, itemorder: rvalue } } if(i > ridIdx) { return { ...l, itemorder: l.itemorder + 1 } } return l }) console.log(orderedList)
上面的代码应该可以工作。 到目前为止,根据我从您的问题中了解到的信息,我们执行以下步骤:
列表
中查找给定rid的项目列表
,并根据第1步找到的索引,默认返回,如果项目索引与上面的索引匹配,则将iteorder返回为右值,并通过增加现有的iteorder来返回如果项目索引大于找到的索引,则值加 1