我正在创建一个包含大量对象的JSON数组,例如:
var JSON = [];
var obj1 = {
"familyId": 5,
"implant": [{
"reference": 12345678,
"quantity": 3,
"origin": "ours",
"lot": null
}]
}
var obj2 = {
"familyId": 5,
"implant": [{
"reference": 12345678,
"quantity": 2,
"origin": "theirs",
"lot": null
}]
}
JSON.push(obj1);
JSON.push(obj2);
如何搜索此JSON数组(使用可能find()
或indexOf()
)来确定原产地为“我们的”的参考数量“12345678”?
答案 0 :(得分:0)
您可以使用Array#find
作为外部数组,使用Array#some
作为内部数组的搜索条件。
var array = [{ "familyId": 5, "implant": [{ "reference": 12345678, "quantity": 3, "origin": "ours", "lot": null }] }, { "familyId": 5, "implant": [{ "reference": 12345678, "quantity": 2, "origin": "theirs", "lot": null }] }],
object = array.find(o => o.implant.some(a => a.reference === 12345678 && a.origin === 'ours'));
console.log(object);

答案 1 :(得分:0)
你可以循环throgh JSON
数组并列出它们 - 演示如下:
var JSON = [];
var obj1 = {
"familyId": 5,
"implant": [{
"reference": 12345678,
"quantity": 3,
"origin": "ours",
"lot": null
}]
}
var obj2 = {
"familyId": 5,
"implant": [{
"reference": 12345678,
"quantity": 2,
"origin": "theirs",
"lot": null
}]
}
JSON.push(obj1);
JSON.push(obj2);
function search(reference, origin) {
var found = [];
JSON.forEach(function(element) {
element.implant.forEach(function(ele){
if(ele.reference == reference && ele.origin == origin) {
this.push(element);
}
}, this);
}, found);
return found;
}
console.log(search(12345678, "ours"));

.as-console-wrapper{top:0;max-height:100% !important;}