1

I want to transform this to an array of values ordered based on an array of keys:

{
  tom: 1,
  jim: 2,
  jay: 3
}

Input -> Output examples:

['jim', 'tom', 'jay'] -> [2, 1, 3]

['jay', 'tom', 'jim'] -> [3, 1, 2]

How can I accomplish this? I'd rather a one line lodash solution.

4 Answers 4

3

You can use lodash's _.at() to get an array of the values in the order that you want:

var data  = {
  tom: 1,
  jim: 2,
  jay: 3
};

var result1 = _.at(data, ['jim', 'tom', 'jay']);
var result2 = _.at(data, ['jay', 'tom', 'jim']);

console.log("['jim', 'tom', 'jay'] -> ", JSON.stringify(result1));
console.log("['jay', 'tom', 'jim'] -> ", JSON.stringify(result2));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

Sign up to request clarification or add additional context in comments.

Comments

2

You could map the values with plain Javascript with Array#map.

var data = { tom: 1, jim: 2, jay: 3 },
    order = ['jim', 'tom', 'jay'],
    result = order.map(k => data[k]);

console.log(result);

Comments

0

const data = {
  tom: 1,
  jim: 2,
  jay: 3
}

const order = ['jay', 'tom', 'jim'];

const result = order.map((item) => data[item]);

console.log(result);

Comments

0
function SortByKeyArray(obj, key_arr) {
    return key_arr.map(k => obj[k]);
}

Or

let SortByKeyArray = (obj, keys) => keys.map(k => obj[k]);

Which is more friendly to me.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.