简体   繁体   English

从数组中获取价值的更简单方法

[英]easier way to get value from array

I have an array with a structure like: 我有一个结构如下的数组:

array = [
    { id: 1001 , info: {bunch of info in here} },
    { id: 1002 , info: {bunch of info in here} }
]

is there a way I can grab all the info of id = 1002 without having to loop through the array with .each()? 有没有一种方法可以获取id = 1002的所有信息,而不必使用.each()遍历整个数组?

No, but you can pre-process: 不,但是您可以预处理:

var map = {};
array.forEach(function(item) {map[item.id] = item.info;});

Then you can access properties by ID much more easily. 然后,您可以更轻松地通过ID访问属性。

In case possible, chnage your array to map, where the key will be ID value and value will be Info. 如果可能,请更改数组以进行映射,其中键将是ID值,而值将是Info。

Something like: 就像是:

array[1002] = [
    { id: 1002 , info: {bunch of info in here} }
]
array[1001] = [
    { id: 1001 , info: {bunch of info in here} }
]

I know the tags are Javascript and Jquery only but have a look at underscorejs. 我知道这些标签仅是Javascript和Jquery,但请看一下underscorejs。 It has a lot of useful stuff to work with array. 使用数组有很多有用的东西。 Fo example where function from underscorejs would give you what you are actually trying to achive. 例如 underscorejs 中的函数将为您提供您实际上想要达到的目标。

Hope it helps! 希望能帮助到你!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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