I have a variable which returns an object. This object has multiple properties, the first property is an array of more objects. I want to access this one by one using javascript and render it using html css and js.
This is my object variable (myObj).
const myJson = item.message;
const myObj = JSON.parse(myJson);
console.log(myObj);
In the first image you can see the returned object that has 2 properties.
In the second image I have expanded the first property which itself is an array of objects.
- I want to access these objects one by one and print them in tables using HTML, CSS and JS
- I want to access object property based on each property index rather than its property name eg: all the object keys will be table headers and all its values will be in data cells. I know if I want to do this without using property name eg: obj.id I have to use for loops, but I can't seem to get this correctly. Would appreciate any help.
CodePudding user response:
this is what i understood from the question.
const data = {courseconfig:[{title:'title1', id:'id1'}]};
for(let i = 0; i < data.courseconfig.length; i ){
const objectKeys = Object.keys(data.courseconfig[i]);
for(let j = 0; j < objectKeys.length; j )
console.log(data.courseconfig[i][objectKeys[j]]);
}
EDIT 1: to access a property of an object which has a name you can use '.name', or ['name'].
EDIT 2: New snippet added
function extractInfo(someArray){
for(let i = 0; i < someArray.length; i ){
const objectKeys = Object.keys(someArray[i]);
for(let j = 0; j < objectKeys.length; j )
console.log(someArray[i][objectKeys[j]]);
}
}
const data = {courseconfig:[{title:'title1', id:'id1'}], filterconfig:[{ title:'title2', id:'id2' }]};
const dataKeys = Object.keys(data);
for(let i = 0; i < dataKeys.length; i ){
if(Array.isArray(data[dataKeys[i]])){
extractInfo(data[dataKeys[i]]);
}
}