I am facing an issue with extracting and displaying only the year from the date property of objects in an array. The current script I have displays all the years for each object instead of tying it to the individual object.
Here is the code snippet:
//array of objects
objArray = [
{
foo: 1,
bar: "December 5, 2020"
},
{
foo: 3,
bar: "April 2, 2019"
},
{
foo: 5,
bar: "January 6, 2018"
}
];
//get year from date
let result = objArray.map((a) => a.bar.substr(-4));
//template literal
function objArrayTemplate(obj) {
return `
<p>Item ${obj.foo}</p>
<p>Year: ${result}</p>
<p>***********</p>
`;
}
//output
document.getElementById("objArrayResult").innerHTML = `${objArray
.map(objArrayTemplate)
.join(" ")}`;
<div id="objArrayResult"></div>