简体   繁体   English

解析JSON,查找值匹配项并存储在数组中

[英]Parse JSON, find matches of values and store in array

I have having trouble figuring out how I can limit my output. 我在弄清楚如何限制输出方面遇到困难。 I have to compare values of each attribute within an object, however I only want 1 output per ID. 我必须比较对象中每个属性的值,但是每个ID仅需要1个输出。

Any thoughts? 有什么想法吗?

//example JSON //示例JSON

var obj1 = {
"Summary" : 
[
    {
        "ID" : "1234", 
        "Name" : "John", 
        "Status" : "Green",
    },
    {
        "ID" : "5678", 
        "Name" : "Mike", 
        "Status" : "Green",
    },
    {
        "ID" : "9012", 
        "Name" : "Tom", 
        "Status" : "Red",
    }

]
};

//my code //我的代码

var attributesvalues = ["Mike", "Green", "Red"];
var sg1 = [];
var k;
var l;


//push name of each attribute value to a new array
//one example
sg1.push(attributesvalues[0]);

 //go through each ID, if name value exist, push the #1, if not, push nothing
 for (k = 0; k < obj1.Summary.length; k++) {
 for (l in obj1.Summary[k]) {
    if (sg1[0] == obj1.Summary[k][l]){
    sg1.push("1");
    }
    else{
    sg1.push("");   
    }
 }

 }

output should look like this - I only want 4 values, name + a 1 or "" for each ID(3) 输出应该看起来像这样-我只想要4个值,每个ID(3)的名称+ 1或“”

sg1 = ["Mike", "", "1", ""] sg1 = [“ Mike”,“”,“ 1”,“”]
sg2 = ["Green", "1", "1", ""] sg2 = [“绿色”,“ 1”,“ 1”,“”]

instead I am getting this - the name + a 1 or "" for each attribute. 相反,我得到这个-每个属性的名称+ 1或“”。

sg1 = ["Mike", "", "", "", "", "1", "", "", "", ""] sg1 = [“ Mike”,“”,“”,“”,“”,“ 1”,“”,“”,“”,“”]
sg2 = ["Green", "", "", "1", "", "", "1", "", "", ""] sg2 = [“绿色”,“”,“”,“ 1”,“”,“,” 1“,”“,”“,”“]

Any additional pointers or tips you could provide would be much appreciated. 您可以提供的任何其他指针或技巧将不胜感激。 I am still trying to get the hang of JS. 我仍在尝试摆脱JS的困扰。

You don't know if you have a match or not until you finish the entire for-in loop. 在完成整个for-in循环之前,您不知道是否有匹配项。

var found;

for (k = 0; k < obj1.Summary.length; k++) {
    found = "";
    for (l in obj1.Summary) { 
        if (obj1.Summary[i][l] == sg1[0]) {
            found = "1";
            break;
        }
    }
    sg1.push(found);
}

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

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