For the json object :
var str={
"roles":[
{
"roleId":"Abcd",
"envRoleName": "0101",
"roleName": "Admin",
"envCode":"HosJ",
"envName":"UoH"
},
{
"roleId":"efgh",
"envRoleName": "0102",
"roldeName": "User",
"envCode":"HosJ",
"envName":"HosJ"
}
]
}
and I have an array const available_roles: Role[] = []
I am trying to insert each object from json array into the Role[]
by
var json = JSON.parse(str); numParams = Object.keys(json.roles[0]).length;
for(j = 0 ; j < json.roles.length ; j++){
if(j % numParams == 0){
available_roles.push ( json.roles[j] );
}
}
The available_roles
array is populated with 10 objects instead of just 2 objects. Can someone explain why this might be, please?
Why don't you just assign the object directly?
var json = JSON.parse(str);
for(j = 0 ; j < json.roles.length ; j++) {
available_roles.push ( json.roles[j] );
}
No need of parse, Just do it directly becoz its already object. JsFiddle
var str={
"roles":[
{
"roleId":"Abcd",
"envRoleName": "0101",
"roleName": "Admin",
"envCode":"HosJ",
"envName":"UoH"
},
{
"roleId":"efgh",
"envRoleName": "0102",
"roldeName": "User",
"envCode":"HosJ",
"envName":"HosJ"
}
]
}
var availableuser = [];
for(j = 0 ; j < str.roles.length ; j++)
{
console.log(str.roles[j])
availableuser.push(str.roles[j]);
}
console.log(availableuser);
str
is already a JSON object. You can use it directly without parsing:
var numParams = Object.keys(str.roles[0]).length;
for(j = 0 ; j < str.roles.length ; j++)
{
if(j % numParams == 0){
available_roles.push ( str.roles[j] );
}
}
Some observations :
str
is already a JSON object
so no need to parse it again. roles
into the available_roles
array diectly. no need to do this type of condition j % numParams == 0
. DEMO
var str = { "roles": [{ "roleId": "Abcd", "envRoleName": "0101", "roleName": "Admin", "envCode": "HosJ", "envName": "UoH" }, { "roleId": "efgh", "envRoleName": "0102", "roldeName": "User", "envCode": "HosJ", "envName": "HosJ" }] }; var json = str; var available_roles = []; for(j = 0 ; j < json.roles.length ; j++){ available_roles.push(json.roles[j]); } console.log(available_roles);
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.