Home > front end >  Help JS loop how to delete is not in conformity with the conditions of sub array
Help JS loop how to delete is not in conformity with the conditions of sub array

Time:09-24

Var array=[
{
Id: 1,
Name: aaa,
Info: [
{
Id: 1,
Adress: beijin
},
{
Id: 2,
Adress: Shanghai
},
.
]
},
{
Id: 2,
Name: BBB,
Info: [
{
Id: 1,
Adress: beijin
},
{
Id: 2,
Adress: Shanghai
},
.
]
}
,...
]; Cycle, if the info of the array element is deleted when the id is not equal to the parent element id, such as {id: 1, name: aaa, info: [{id: 1, adress: beijin}, {id: 2, adress: Shanghai},... Id=1} in the father, the info id is not equal to 1 are all deleted, use for splice is found in the info all deleted is empty,

CodePudding user response:

for(var i=0; I
Var id=array [I]. Id;
Var list=[]
for(var j=0; J
If (array [I]. Info [j]. Id==id) {
List. Push (array [I]. Info [j])
}
}
Array [I]. Info=list;

}

CodePudding user response:

Array. The map ((item, index)=& gt; {

Var list=item. Info. The filter ((voo)=& gt; {

Return the item. The id==voo. Id;
})
Array [index]. Info=list
})

CodePudding user response:

 
Var array=[{
Id: 1,
Name: "aaa",
Info: [{
Id: 1,
Adress: "beijin
"}, {
Id: 2,
Adress: "Shanghai"
}]
}, {
Id: 2,
Name: "BBB,"
Info: [{
Id: 1,
Adress: "beijin
"}, {
Id: 2,
Adress: "Shanghai"
}]
}];

for (var i=0; I & lt; Array. The length; I++) {
Var info=array [I] the info;
For (var j=info length - 1. J & gt;=0; J -)
If (info [j]. Id!=array [I]. Id)
Info. Splice (j, 1);
}
The console. The log (array);
  • Related