如何使用javascript更新屬性並取得數組物件中連續順序具有屬性值的結果
P粉980815259
P粉980815259 2024-04-04 13:32:46
0
1
512

我有物件陣列list,參數ridrorder被傳遞。

-> 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粉980815259
P粉980815259

全部回覆(1)
P粉865900994

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)

上面的程式碼應該可以工作。 到目前為止,根據我從您的問題中了解到的信息,我們執行以下步驟:

  1. 清單中找出給定rid的項目
  2. 現在映射列表,並根據步驟1找到的索引,預設返回,如果項目索引與上面的索引匹配,則將iteorder返回為右值,並透過增加現有的iteorder來傳回如果項目索引大於找到的索引,則值加1
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板