通过其中一个键的值,在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]] … }更多推荐
发布评论