简体   繁体   English

如何在javascript json数组对象中获取相同id的不同值

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

How to get same id different values in javascript json array object and push it in array.如何在javascript json数组对象中获取相同id的不同值并将其推送到数组中。

This is actual json data,这是实际的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
    }];

And the output i want, for wardid: 3和我想要的输出,对于wardid:3

    [{
        "areaid": 18
    },{
        "areaid": 17
    },{
        "areaid": 16
    }]

for wardid: 4监护人:4

    [{
        "areaid": 21
    },{
        "areaid": 20
    },{
        "areaid": 19
    }]

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.只需使用data[i].wardid从一个简单的for loop内部检索病房 ID,并将相同的 ID 与任何值进行比较,然后data[i].wardid检索同一对象的区域 ID 值。

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.在下面的代码片段中,我将搜索到的病房 ID 的相应区域 ID 附加到新数组和 div 中以更好地说明代码。 Check the Code Snippet or this jsFiddle to see how the following code works:检查代码片段或此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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM