-1

I'm creating a JSON array with lots of objects, like:

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

How can I search this JSON array (using maybe find() or indexOf()) to determine the quantity of reference "12345678" with origin "ours"?

Brad
  • 1,019
  • 1
  • 9
  • 22

2 Answers2

0

You could use Array#find for the outer array and Array#some for the inner array with the search conditions.

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);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

You can loop throgh JSON array and list out them - demo below:

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;}
kukkuz
  • 41,512
  • 6
  • 59
  • 95