2015-11-03 6 views
1

У меня есть JSON объект:Петля через объект JSON и проверить, если конкретный объект существует

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

У меня есть требование, где в я хотел бы, чтобы проверить, есть ли мой объект JSON конкретная форма; если да, то проверьте, есть ли у него определенный ребенок.

eg: check if box 1 exists if yes then check if it has child if yes then check if it has 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; 
     }); 
    } 
    } 

Это не похоже на работу, так как даже после того, как я вернусь ложь он все еще продолжает идти в цикле. Я бы хотел разбить цикл, если найду совпадение.

Любое предложение?

+1

Используйте обычный для цикла, то, вы не можете разбить/возврат от использования '.map()'. Поскольку 'return' предназначен для текущего обратного вызова, а не для всей операции. –

ответ

2

Вам нужно перебрать все массивы, что вам нужно.

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>');

-1

Я думаю, что это поможет.

for(var i=DependantArr.length;i>=0;i--) { 
        return DependantArr[i].box == 1 && DependantArr[i].child.length!=0 && 
    DependantArr[i].child[0].boxId==2; 

      } 
+0

проверьте, имеет ли он child boxId = 2, и у вас много ошибок в вашем коде, например: 'DependantArr [i] .box.длина' – Ziki

+0

@ Ziki .. обновленный. спасибо –

-1

Если это единственный случай, вам нужно проверить, вы можете использовать это:

var DependantArr = [{"box": 1, "parent": [], "child": [{"boxId": 3}]}, {"box": 2, "parent": [{"boxId": 1}], "child": []}]; 
var $hasDependancy = DependantArr.some(function(thisBox) { 
    if ((thisBox.box === 1) && (thisBox.hasOwnProperty('child'))) { 
     return thisBox.child.filter(function(thisChild) { 
      return thisChild.boxId === 2; 
     }).length > 0; 
    } 
}); 
0

Попробуйте

data.forEach(function (el) { 
Object.keys(el).forEach(function (property) { 
    if (el[property] === 'your value to check') { 
     // do whatever you need here 
    } 
    }); 
}); 
1

Создать функцию, которая будет вызывать filter на массиве и возвращает его. Возвращаемое значение будет массивом, содержащим найденный объект (ы), который соответствует (и) вашим условиям (состояниям).

Demo Отрывок: (проверка консоли)

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

 
function search(id, childId) { 
 
    return json.filter(function(obj) { 
 
     if ((obj.box == id) && (obj.child) && (obj.child.length > 0)) { 
 
      return obj.child.filter(function(child) { 
 
       return (child.boxId == childId); 
 
      }); 
 
     } 
 
    }); 
 
} 
 

 
console.log(search('1', '2')[0]); 
 
console.log(search('2', '2')[0]);

+1

"проверьте, если у него есть child boxId = 2" – Ziki

+0

Спасибо @Ziki. Я полностью пропустил эту часть. Обновлено. – Abhitalks

1

Вы можете использовать рекурсию. вызывать ту же функцию рекурсивно, чтобы проверить, действительно ли элемент, который вам нужен, в массиве или нет.

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

 
var found = false; 
 
function validateJson(data, box, boxId){ 
 
    for(key in data){ 
 
    if((data[key].constructor === Object || data[key].constructor === Array) && (key !== box && data[key] !== 1 || key !== boxId && data[key] !== 2)){ 
 
     arguments.callee(data[key]); // <---calls the same function again. 
 
    } else { 
 
     found = true; // true only in the case of if "box":1 and "boxId" : 2 
 
    } 
 
    } 
 
    return found; 
 
} 
 
var result = validateJson(json, "box", "boxId"); 
 
document.body.innerHTML = '<pre> found : '+JSON.stringify(result) + '</pre>';

Смежные вопросы