将对象转换为具有给定顺序的数组

时间:2016-09-20 18:24:04

标签: javascript arrays lodash

order = ['mercury', 'venus', 'earth', 'mars', 'jupiter', 'saturn', 'uranus', 'neptune', 'pluto'];

var scrambled = {
  pluto : 'pluto very far',
  mars: 'mars very near',
  saturn: 'saturn dnt care',
  jupiter: 'jupiter',
  uranus : 'uranus',
  earth: 'earth',
  mercury: 'mercury',
  venus: 'venus',
  neptune: 'neptune'
};

需要将对象提取为具有给定顺序的数组

我正在寻找一种解决方案,可以解决最多2到3行。

3 个答案:

答案 0 :(得分:3)

不需要任何外部库使用本机JavaScript Array#map方法。

// iterate over order array
var res = order.map(function(k) {
  // generate array element based 
  // on the order array element
  return scrambled[k];
});

// with ES6 arrow function

var res = order.map(k => scrambled[k]);



order = ['mercury', 'venus', 'earth', 'mars', 'jupiter', 'saturn', 'uranus', 'neptune', 'pluto'];

var scrambled = {
  pluto: 'pluto very far',
  mars: 'mars very near',
  saturn: 'saturn dnt care',
  jupiter: 'jupiter',
  uranus: 'uranus',
  earth: 'earth',
  mercury: 'mercury',
  venus: 'venus',
  neptune: 'neptune'
};

var res = order.map(function(k) {
  return scrambled[k];
});

console.log(res);




答案 1 :(得分:1)

您可以使用lodash的_.at()

var order = ['mercury', 'venus', 'earth', 'mars', 'jupiter', 'saturn', 'uranus', 'neptune', 'pluto'];

var scrambled = {
  pluto : 'pluto very far',
  mars: 'mars very near',
  saturn: 'saturn dnt care',
  jupiter: undefined,
  uranus : 'uranus',
  earth: 'earth',
  mercury: 'mercury',
  venus: 'venus',
  neptune: 'neptune'
};

var result = _.at(scrambled, order);

console.log('with undefineds', result);

var result = _.filter(_.at(scrambled, order), _.negate(_.isUndefined)); // filter out all undefined items

console.log('without undefineds', result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.1/lodash.min.js"></script>

答案 2 :(得分:0)

Pure JS应该这样做

var order = ['mercury', 'venus', 'earth', 'mars', 'jupiter', 'saturn', 'uranus', 'neptune', 'pluto'],
scrambled = {
  pluto : 'pluto very far',
  mars: 'mars very near',
  saturn: 'saturn dnt care',
  jupiter: 'jupiter',
  uranus : 'uranus',
  earth: 'earth',
  mercury: 'mercury',
  venus: 'venus',
  neptune: 'neptune'
},
   sorted = order.map(k => scrambled[k]);
console.log(sorted);