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.
Any thoughts?
//example 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)
sg1 = ["Mike", "", "1", ""]
sg2 = ["Green", "1", "1", ""]
instead I am getting this - the name + a 1 or "" for each attribute.
sg1 = ["Mike", "", "", "", "", "1", "", "", "", ""]
sg2 = ["Green", "", "", "1", "", "", "1", "", "", ""]
Any additional pointers or tips you could provide would be much appreciated. I am still trying to get the hang of JS.
You don't know if you have a match or not until you finish the entire for-in
loop.
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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.