[英]Order array of object by another array of object in javascript
如何通過另一個對象數組對對象數組進行排序。
這是我的代碼:
let arrayItem = [
{
'id': '#id1',
'name': 'one',
'bundle': 'bundle1'
},
{
'id': '#id2',
'name': 'two',
'bundle': 'bundle2'
},
{
'id': '#id3',
'name': 'three',
'bundle': 'bundle3'
}
]
這是用於排序的數組:
let orderItem = [
{
'id': '#id3',
'name': 'three'
},
{
'id': '#id1',
'name': 'one',
},
{
'id': '#id2',
'name': 'two'
}
]
我需要像這樣的數據:
let resultItem = [
{
'id': '#id3',
'name': 'three',
'bundle': 'bundle3'
},
{
'id': '#id1',
'name': 'one',
'bundle': 'bundle1'
},
{
'id': '#id2',
'name': 'two',
'bundle': 'bundle2'
}
]
我想通過多個鍵通過另一個對象數組對對象數組進行排序。
謝謝
由於orderArray
有對象數組,因此您首先需要找到該訂單對象的索引,然后獲取index
以對原始數組進行排序:
let arrayItem = [ { 'id': '#id1', 'name': 'one', 'bundle': 'bundle1' }, { 'id': '#id2', 'name': 'two', 'bundle': 'bundle2' }, { 'id': '#id3', 'name': 'three', 'bundle': 'bundle3' } ]; let orderItem = [ { 'id': '#id3', 'name': 'three' }, { 'id': '#id1', 'name': 'one', }, { 'id': '#id2', 'name': 'two' } ]; arrayItem.sort(function(a, b){ var aIndex = orderItem.findIndex(({id, name}) => a.id===id && a.name===name); var bIndex = orderItem.findIndex(({id, name}) => b.id===id && b.name===name); return aIndex - bIndex; }); console.log(arrayItem);
您可以使用@Ankit Agarwal建議的“ 排序” 。
或者,您可以使用下面的簡單行使其變得更適合您。 這將達到目的。
var orderedItem = orderItem.map(orderObj =>
arrayItem.find(actualObj => actualObj.id === orderObj.id))
我只是在orderItem上運行
map
,在arrayItem上find
相應的對象,然后從arrayItem返回該對象。
希望能幫助到你..
您可以使用Map
來存儲索引/順序,然后使用索引的差量對數組進行排序。
var arrayItem = [{ id: '#id1', name: 'one', bundle: 'bundle1' }, { id: '#id2', name: 'two', bundle: 'bundle2' }, { id: '#id3', name: 'three', bundle: 'bundle3' }], orderItem = [{ id: '#id3', name: 'three' }, { id: '#id1', name: 'one', }, { id: '#id2', name: 'two' }], order = new Map(orderItem.map(({ id }, i) => [id, i])); arrayItem.sort((a, b) => order.get(a.id) - order.get(b.id)); console.log(arrayItem);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.