我有一个 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/