Reputation: 523
I have the following array
var array = {"week1":[{"id":1,"name":"x","mark":"20"},{"id":2,"name":"y","mark":"30"}],"week2":[{"id":1,"name":"x","mark":"40"},{"id":2,"name":"y","mark":"60"},{"id":3,"name":"z","mark":"10"}]}
and I also have an array of student Ids as follows
var studentId = ["1","2","3"]
I want to iterate through array and insert the missing student ids into each week and set mark as zero.
var keys = Object.keys(array);
for(var x =0; x<studentId .length; x++)
{
var boolFlag = false;
for(var i=0; i<keys.length;i++)
{
for(var j=0; j=array [keys[i]].length; j++ )
{
if(studentId [x].id == array [keys[i]][j].id)
{
boolFlag = true;
break;
}
}
if(!boolFlag )
{
array [keys[i]].push({id:studentId [x].id, mark:0});
}
}
}
This works if all the weeks don't contain a studentId completely. But if any of the weeks contain the studentId then this is not inserting the id correctly.What is wrong in my code?
expected result:
var result = {"week1":[{"id":1,"name":"x","mark":"20"},{"id":2,"name":"y","mark":"30"},{"id":3,"mark":"0"}],"week2":[{"id":1,"name":"x","mark":"40"},{"id":2,"name":"y","mark":"60"},{"id":3,"name":"z","mark":"10"}]}
UPDATE
var studentId = [{id:"1", name:"x"},{id:"2", name:"y"},{id:"3", name:"z"}]
Upvotes: 0
Views: 44
Reputation: 13498
var array = {
"week1":[
{"id":1,"name":"x","mark":"20"},
{"id":2,"name":"y","mark":"30"}
],
"week2":[
{"id":1,"name":"x","mark":"40"},
{"id":2,"name":"y","mark":"60"},
{"id":3,"name":"z","mark":"10"}
]
};
var studentId = [
{id:"1", name:"x"},
{id:"2", name:"y"},
{id:"3", name:"z"}
]
for(var week in array){
for(var stId of studentId){
var weekVal = array[week];
if(!weekVal.filter(function(st){ return st.id == stId.id; })[0])
weekVal.push({id:stId.id, name: stId.name, mark:"0"});
}
}
console.log(array);
Upvotes: 1