使用Javascript / jQuery的:值获取键嵌套数组中 [英] Javascript/jQuery: Get key by value inside a nested array

查看:191
本文介绍了使用Javascript / jQuery的:值获取键嵌套数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  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 calling data[1].obj2 - the key would be 1 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 know value4 belongs to obj2 and I need to find it's corresponding obj1.

I'm guessing the way to solve this is to figure out what the i should be in data[i] for value4 and then simply call data[i].obj1. But how do I get that i?

解决方案

I'm guessing the way to solve this is to figure out what the i should be in data[i] for value4 and then simply call data[i].obj1.

obj2, you mean, not obj1.

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 use some:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆