patz
patz

Reputation: 1316

convert object into an array with the given order

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

need to extract the object into an array with the given order,

I am looking for a solution which can solve this is max of 2 to 3 lines.

Upvotes: 1

Views: 71

Answers (3)

Ori Drori
Ori Drori

Reputation: 191986

You can use lodash's _.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>

Upvotes: 1

Redu
Redu

Reputation: 26161

Pure JS this should do it

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

Upvotes: 0

Pranav C Balan
Pranav C Balan

Reputation: 115232

There is no need of any external library use native JavaScript Array#map method.

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

Upvotes: 3

Related Questions