如何在javascript json数组对象中获取相同ID的不同值并将其推入数组。
这是实际的json数据,
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
}];
我想要的输出, 对于病房:3
[{
"areaid": 18
},{
"areaid": 17
},{
"areaid": 16
}]
对于守卫:4
[{
"areaid": 21
},{
"areaid": 20
},{
"areaid": 19
}]
答案 0 :(得分:0)
只需使用 data[i].wardid
即可从简单的for loop
内部检索病房ID,并将该ID与任何值进行比较,从而反过来检索那个对象。
在以下代码片段中,我将搜索到的Ward ID的相应Area ID附加到新数组以及div上,以更好地说明代码。检查代码段或此jsFiddle,以查看以下代码的工作原理:
/* 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>