I've tried to reach an element in object inside an array which is an element in an object inside an array. Look at the code under. The thirdElementInObject has variable length. My plan is to make list element with every object in the mainArray. I haven't made it with the elements in the thirdElementInObject array. Does anyone know how I can do this?
mainArray = [
{firstElementInObject: xyz,
secondElementInObject: abc,
thirdElementInObject: [
{name: zzz,
age: aaa,
},
{name: cde,
age: 123,
},
],
},
{firstElementInObject: xyz,
secondElementInObject: abc,
thirdElementInObject: [
{name: xxx,
age: yyy,
},
{name: abc,
age: def,
},
{name: abc,
age: def,
}
],
}
]
const parentElementDash = document.querySelector('.mainArrayUl');
const updateHTML = function () {
if (mainArray.length > 0) {
let result = mainArray.map(element => {
return `
<li>
<p>${element.firstElementInObject}</p>
<p>${element.secondElementInObject}</p>
/* Here I want to write the name in the
thirdElementInObject. */
</li>`
});
parentElementDash.innerHTML = result.join('');
}
}
updateHTML();
CodePudding user response:
- You can get all the names as an array using
.map()
. - You can then use
.join()
to convert the array to string and insert it in the HTML.
Try this
var mainArray = [
{
firstElementInObject: 'xyz',
secondElementInObject: 'abc',
thirdElementInObject: [
{name: 'zzz', age: 'aaa',},
{name: 'cde', age: 123,},
],
},
{
firstElementInObject: 'xyz',
secondElementInObject: 'abc',
thirdElementInObject: [
{name: 'xxx', age: 'yyy',},
{name: 'abc', age: 'def',},
{name: 'abc', age: 'def',}
],
}
]
const parentElementDash = document.querySelector('.mainArrayUl');
const updateHTML = function () {
if (mainArray.length > 0) {
let result = mainArray.map(element => {
return `
<li>
<p>${element.firstElementInObject}</p>
<p>${element.secondElementInObject}</p>
<p>${element.thirdElementInObject.map(({name}) => name).join(', ')}</p>
</li>`
});
parentElementDash.innerHTML = result.join('');
}
}
updateHTML();
<ul ></ul>