[英]I want to sort the objects in another array order
①有這樣的數組。
const array = ['a', 'b', 'c', 'd', 'E'];
②有一個object。
const obj = {
'b': ['aa', 'bb', 'cc'],
'a': ['ac', 'bc', 'cs'],
'c': ['as', 'b', 'c_1'],
'E': ['a_4', 'b_4', 'c_4'],
'd': ['a_4', 'b_4', 'c_4']
};
當您想根據①的排列順序重新排列這些時。
我希望結果是這樣的。
const obj = {
'a': ['ac', 'bc', 'cs'],
'b': ['aa', 'bb', 'cc'],
'c': ['as', 'b', 'c_1'],
'd': ['a_4', 'b_4', 'c_4'],
'E': ['a_4', 'b_4', 'c_4']
};
是否可以僅使用 map function 並排序?
const array = ['a', 'b', 'c', 'd', 'E']; const obj = { 'b': ['aa', 'bb', 'cc'], 'a': ['ac', 'bc', 'cs'], 'c': ['as', 'b', 'c_1'], 'E': ['a_4', 'b_4', 'c_4'], 'd': ['a_4', 'b_4', 'c_4'] }; // console.log(JSON.stringify(obj)) const res = Object.keys(obj).sort((a, b) => array.indexOf(a) - array.indexOf(b)).reduce((a, k) => ({...a, [k]: obj[k] }), {}) console.log(JSON.stringify(res))
使用Object.fromEntries()
和Object.entries()
const array = ['a', 'b', 'c', 'd', 'E']; const obj = { 'b': ['aa', 'bb', 'cc'], 'a': ['ac', 'bc', 'cs'], 'c': ['as', 'b', 'c_1'], 'E': ['a_4', 'b_4', 'c_4'], 'd': ['a_4', 'b_4', 'c_4'] }; // console.log(JSON.stringify(obj)) const res = Object.fromEntries(Object.entries(obj).sort((a, b) => array.indexOf(a[0]) - array.indexOf(b[0]))) console.log(JSON.stringify(res))
我認為我們不需要排序,因為我們的目標是根據數組排列obj 。
const array = ['a', 'b', 'c', 'd', 'E']; const obj = { 'b': ['aa', 'bb', 'cc'], 'a': ['ac', 'bc', 'cs'], 'c': ['as', 'b', 'c_1'], 'E': ['a_4', 'b_4', 'c_4'], 'd': ['a_4', 'b_4', 'c_4'] }; let result = array.reduce((accumulator, currentItem)=>{ accumulator[currentItem] = obj[currentItem]; return accumulator; },{}); console.log(result)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.