[Solved] How to get same id different values in javascript json array object


Just use data[i].wardid to retrieve the Ward ID from inside a simple for loop and compare that same ID with any value that which in turns, retrieve the Area ID value of that same object.

In the following code snippet, I appended the corresponding Area IDs of the searched Ward ID to a new array as well as to a div to illustrate the code better. Check the Code Snippet or this jsFiddle to see how the following code works:

/* JavaScript */
var val = document.getElementById("val");
var btn = document.getElementById("btn");
var output = document.getElementById("output");
var outPutArray = [];

function checkId(){
  outPutArray = [];
  output.innerHTML = `<p>The following wards have that ID:</p>`;
  if(!val.value) {
    alert('Please input ID');
  } else {
  	
    for(i=0; i < data.length; i++) {
    	if(data[i].wardid == val.value) {
        var x = {};
        x.warid = data[i].wardid;
        x.areaid = data[i].areaid;   
        outPutArray.push(x);
      	output.innerHTML += `<div>Area ${data[i].areaid}</div>`;
      }
    }
    console.log(outPutArray);
  }  
}

btn.addEventListener("click", checkId);

var data = [{"areaid":25,"wardid":5},{"areaid":24,"wardid":5},{"areaid":23,"wardid":5},{"areaid":22,"wardid":5},{"areaid":21,"wardid":4},{"areaid":20,"wardid":4},{"areaid":19,"wardid":4},{"areaid":18,"wardid":3},{"areaid":17,"wardid":3},{"areaid":16,"wardid":3}];
<!-- HTML -->
<input type="number" id="val" min="3" max="5" name="wardId" />
<button id="btn">
Check Id
</button>
<div id="output">
<p>
The following Areas have that Ward ID:
</p>
</div>

2

solved How to get same id different values in javascript json array object