javascript - 遍历 JSON 对象并检查特定对象是否存在

标签 javascript jquery json

我有一个 JSON 对象:

[{"box":1,"parent":[],"child":[{"boxId":2}]},{"box":2,"parent":[{"boxId":1}],"child":[]}]

我有一个要求,我想检查我的 JSON 对象是否有特定的框;如果是,则检查它是否有特定的 child 。

例如:检查框 1 是否存在 如果是的话 检查它是否有 child 如果是的话 检查它是否有子 boxId=2

我如何在 javascript/jquery 中做到这一点?

我是这样尝试的:

   var DependantArr=myJSON;
   var $hasDependancy;
   DependantArr.map(function (boxes) {
    if (boxes.box == 2) {
        if (boxes.child.length != 0) {
           boxes.child.map(function (child) {
           $hasDependancy = true;
           return false;
         });
     }
   }

这似乎不起作用,因为即使在我返回 false 之后它仍然继续循环。如果找到匹配项,我想打破循环。

有什么建议吗?

最佳答案

您需要遍历所有数组,您需要。

var array = [{ "box": 1, "parent": [], "child": [{ "boxId": 2 }] }, { "box": 2, "parent": [{ "boxId": 1 }], "child": [] }];

function check() {
    var found = false;
    array.some(function (a) {
        if (a.box === 1) {
            Array.isArray(a.child) && a.child.some(function (b) {
                if (b.boxId === 2) {
                    found = true;
                    return true;
                }
            });
            return true;
        }
    });
    return found;
}

document.write(check());

另一种解决方案采用更通用的方法,使用给定的对象作为所需项目的模式。

[
    { condition: { box: 1 }, nextKey: 'child' },
    { condition: { boxId: 2 } }
]

var array = [{ "box": 1, "parent": [], "child": [{ "boxId": 2 }] }, { "box": 2, "parent": [{ "boxId": 1 }], "child": [] }];
    
function check(array, conditions) {

    function c(a, index) {
        var el = conditions[index],
            k = Object.keys(el.condition),
            v = el.condition[k],
            found = false;

        return Array.isArray(a) &&
            a.some(function (b) {
                if (b[k] === v) {
                    found = true;
                    if (conditions.length > index + 1) {
                        found = c(b[el.nextKey], index + 1);
                    }
                    return true;
                }
            }) &&
            found;
    }
    return c(array, 0);
}

document.write(check(array, [{ condition: { box: 1 }, nextKey: 'child' }, { condition: { boxId: 2 } }])+'<br>');
document.write(check(array, [{ condition: { box: 2 }, nextKey: 'parent' }, { condition: { boxId: 1 } }]) + '<br>');

关于javascript - 遍历 JSON 对象并检查特定对象是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33493044/

相关文章:

javascript - 克拉姆当延伸

通过 ajax 调用使用动态参数的不同时刻的 Javascript 多个倒数计时器

javascript - 改变元素的类别,在每次鼠标点击

java - 使用 Retrofit 时,当回复有时是对象有时是数组时,如何解析 JSON 回复?

javascript - 将数据转换为数组数组

javascript - Rails Step by Step Forms - 几乎转换为 Ajax - 除了浏览器后退按钮

jquery - .live() jQuery - 如何更改我的事件

java - JSONParser 在位置 0 处返回意外字符 ()

c# - 如何在 C#.Net 中处理来自 Webservice 的海量 JSON 数据

javascript - ajax 调用后应用 Knockout 绑定(bind)