基于数组排序对象以生成排序数组

问题描述 投票:3回答:2

当我显示它时,对象不保证顺序,所以我必须将现有对象转换为数组,但是按照顺序。

我有这个数组作为命令[1,2,3]

这是我的原始输入aka源

{'2': 'two',
'3': 'three',
'1':'one'}

如何创建一个函数来生成一个新的数组,其中的顺序遵循上面的排序键?

我陷入了这个阶段

//expected 
['one', 'two', 'three']
const order = ['1', '2', '3']
const source = {
  '2': 'two',
  '3': 'three',
  '1': 'one'
}

let sorted = Object.keys(source).map(o => {
  //return order.includes(o) ? //what to do here : null
})

我想我必须在循环内做循环。

javascript arrays ecmascript-6
2个回答
3
投票

可以简单地映射order数组并从source返回相应的值。除此之外的任何事情都使它复杂化

const order = ['1', '2', '3']
const source = {
  '2': 'two',
  '3': 'three',
  '1': 'one'
}

const sorted = order.map(n=>source[n])

console.log(sorted)

0
投票

您可以减少排序数组,并从源对象中查找相关的字符串。该方法仅使用一个循环,因此更有效。

const order = ['1', '2', '3', '4', '5'];
const source = {
  '2': 'two',
  '5': 'five',
  '3': 'three',
  '1': 'one',
  '4': 'four'
};

let sorted = order.reduce((obj, item) => {
  obj.push(source[item]);
  return obj;
}, []);

console.log(sorted);
© www.soinside.com 2019 - 2024. All rights reserved.