简体   繁体   English

我想以另一个数组顺序对对象进行排序

[英]I want to sort the objects in another array order

①There is an array like this. ①有这样的数组。

const array = ['a', 'b', 'c', 'd', 'E'];

②There is an object. ②有一个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']
};

When you want to rearrange these according to the arrangement order of ①.当您想根据①的排列顺序重新排列这些时。

I want the result to be like this.我希望结果是这样的。

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']
};

Is it possible to do it only with the map function and sort?是否可以仅使用 map function 并排序?

Using indexOf() and reduce()使用indexOf()reduce()

 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))

Using Object.fromEntries() and Object.entries()使用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))

I think we don't need sort because, our goal is to arrange the obj in terms of array .我认为我们不需要排序,因为我们的目标是根据数组排列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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM