使用Javascript / jQuery的:值获取键嵌套数组中 [英] Javascript/jQuery: Get key by value inside a nested array
问题描述
VAR myJSON =
{数据:
[{OBJ1:值1
OBJ2:VALUE2}, {OBJ1:值3
OBJ2:VALUE4}, {OBJ1:值5,
OBJ2:value6}]
};
我有类似上述多维数组。关键是<$ C - 在上面的例子中,我可以通过调用数据[1] .obj2
获得 VALUE4
$ C> 1 在这种情况下。
我的问题:我有 VALUE4
但我不知道它在数组中(在按键方面)。我知道 VALUE4
属于 OBJ2
,我需要找到它对应的 OBJ1
。
我猜解决这个问题的方法是要弄清楚什么 I
应该在数据[I]
为 VALUE4
然后只需拨打数据[I] .obj1
。但是,我怎么得到 I
?
我猜解决这个问题的方法是要弄清楚什么
I
应该在数据[I]
为VALUE4
然后只需拨打数据[I] .obj1
。
块引用>
OBJ2
,你的意思是,不是OBJ1
。
但我怎么得到
I
?
块引用>您搜索。这是一个简单的循环。
VAR我;
对于(i = 0; I&LT; myJSON.data.length ++我){
如果(myJSON.data [I] .obj2 ===值4){
// 找到了
打破;
}
}
如果(ⅰ&下; myJSON.data.length){
//发现了它,它在指数`i`
}或者一个系统,你可以依赖于ES5的
的forEach
(或者因为发动机有它本身,还是因为你已经添加了一个垫片):VAR我;
myJSON.data.forEach(功能(入口,指数){
如果(entry.obj2 ===值4){
I =指数;
}
};
如果(typeof运算我!==未定义){
// 找到了
}您不能停止
的forEach
早,所以,做一些不必要的循环。你可以使用部分
:VAR我;
myJSON.data.some(功能(入口,指数){
如果(entry.obj2 ===值4){
I =指数;
返回true; //停止循环
}
};
如果(typeof运算我!==未定义){
// 找到了
}var myJSON = {"data": [{"obj1":"value1", "obj2":"value2"}, {"obj1":"value3", "obj2":"value4"}, {"obj1":"value5", "obj2":"value6"}] };
I've got a multidimensional array similar to above. In the above example I can get
value4
by callingdata[1].obj2
- the key would be1
in this case.My problem: I've got
value4
but I don't where it is inside the array (in terms of the key). I knowvalue4
belongs toobj2
and I need to find it's correspondingobj1
.I'm guessing the way to solve this is to figure out what the
i
should be indata[i]
forvalue4
and then simply calldata[i].obj1
. But how do I get thati
?解决方案I'm guessing the way to solve this is to figure out what the
i
should be indata[i]
forvalue4
and then simply calldata[i].obj1
.
obj2
, you mean, notobj1
.But how do I get that
i
?You search for it. It's a simple loop.
var i; for (i = 0; i < myJSON.data.length; ++i) { if (myJSON.data[i].obj2 === "value4") { // Found it break; } } if (i < myJSON.data.length) { // Found it, it's at index `i` }
Or on a system where you can rely on ES5's
forEach
(either because the engine has it natively, or because you've added a shim):var i; myJSON.data.forEach(function(entry, index) { if (entry.obj2 === "value4") { i = index; } }; if (typeof i !== "undefined") { // Found it }
You can't stop a
forEach
early, so that does some unnecessary looping. You could usesome
:var i; myJSON.data.some(function(entry, index) { if (entry.obj2 === "value4") { i = index; return true; // Stops loop } }; if (typeof i !== "undefined") { // Found it }
这篇关于使用Javascript / jQuery的:值获取键嵌套数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!