简体   繁体   中英

how to get values of objects as array, given keys list?

I have an object as follows,

obj = {
  '1': {val: 1},
  '2': {val: 2},
  '3': {val: 3},
  '4': {val: 4},
  ...
}

Given keys list(as an Array ), I want to get all values list(as an Array ).

For example,

If the keys list is ['3', '4'] , the output would be [{val: 3}, {val: 4}]

I tried as follows

_.values(_.pick(obj, ['3', '4']))

This works but it does two iterations. Is there any way to achieve the same in a single iteration. Thanks in advance.

To create an array of values from selected object propsin Lodash use _.at() :

 var obj = { '1': {val: 1}, '2': {val: 2}, '3': {val: 3}, '4': {val: 4} }; var result = _.at(obj, ['3', '4']); console.log(result); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script> 

For something as simple as picking a few properties form a object, why not just use plain JS?

 const obj = { '1': { val: 1 }, '2': { val: 2 }, '3': { val: 3 }, '4': { val: 4 } } const keys = ['1', '3']; const result = []; for (let i = 0; i < keys.length; i++) { obj[keys[i]] && result.push(obj[keys[i]]); } console.log(result); 

It doesn't get faster than that. Especially not with libraries like lodash, that need to iterate multiple times to cover all kinds of corner cases you're never going to have to bother with.

Or, even faster by storing the object access in a temporary variable, thanks to @KoushikChatterjee :

 const obj = { '1': { val: 1 }, '2': { val: 2 }, '3': { val: 3 }, '4': { val: 4 } } const keys = ['1', '3']; const result = []; let temp; for (let i = 0; i < keys.length; i++) { (temp = obj[keys[i]]) && result.push(temp); } console.log(result); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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