按键值在Object Array中查找元素(Find element in Object Array by key value)

编程入门 行业动态 更新时间:2024-10-10 08:22:15
按键值在Object Array中查找元素(Find element in Object Array by key value)

通过其中一个键的值,在Object Array中查找元素(Object)的最佳结构解决方案是什么。

例如,我们有数组:

var someArray = [ {id:17, color:'black', width:50}, {id:34, color:'red', width:150}, {id:49, color:'gree', width:10} ]

我们需要找到一个id-key = 34的Object。

每次我们都要做循环来找到对象。 我想重组并拥有对象而不是像这样的数组:

var someObject = { 17: {id:17, color:'black', width:50}, 34: {id:34, color:'red', width:150}, 49: {id:49, color:'gree', width:10} }

现在我们可以一步完成someObject [34] ,但是如果我们想要保持秩序呢?

提前致谢。

What is the best structure solution for find element(Object) in Object Array by value of one of the keys.

For example we have array:

var someArray = [ {id:17, color:'black', width:50}, {id:34, color:'red', width:150}, {id:49, color:'gree', width:10} ]

and we need to find an Object with id-key = 34.

And each time we will have to do the loop to find the object. I thought about restructuring and having object instead of array like so:

var someObject = { 17: {id:17, color:'black', width:50}, 34: {id:34, color:'red', width:150}, 49: {id:49, color:'gree', width:10} }

Now we can do it in one step someObject[34], BUT what if we want to keep the order?

Thanks in advance.

最满意答案

我想过重组并拥有对象而不是数组

是的,没关系。

但如果我们想保留订单怎么办?

我倾向于使用一个额外的数组,包含正确顺序的键,比如

var order = [17, 34, 47];

要循环它们,你可以使用

for (var i=0; i<order.length; i++) { … someObject[order[i]] … }

I thought about restructuring and having object instead of array

Yes, that's fine.

BUT what if we want to keep the order?

I tend to use an extra array that contains the keys in the correct order, like

var order = [17, 34, 47];

To loop them, you'd use

for (var i=0; i<order.length; i++) { … someObject[order[i]] … }

更多推荐

本文发布于:2023-08-03 20:02:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1396166.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:按键   元素   Object   key   Array

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!