[英]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
). 给定键列表(作为
Array
),我想获取所有值列表(作为Array
)。
For example, 例如,
If the keys list is ['3', '4']
, the output would be [{val: 3}, {val: 4}]
如果键列表为
['3', '4']
,则输出为[{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()
: 要从Lodash中的选定对象道具创建值数组,请使用
_.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? 对于从一个对象中选取一些属性这样简单的事情,为什么不只使用普通的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.
尤其是对于像lodash这样的库,不需要进行多次遍历,以涵盖您永远不必费心的各种极端情况。
Or, even faster by storing the object access in a temporary variable, thanks to @KoushikChatterjee : 或者,通过@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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.