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();
.map()
..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 class="mainArrayUl"></ul>
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.