I am trying to get two objects from array using the splice() method. But it is not working as expected. Please guide me where i am wrong or help me to fix this. if anybody can modify this code to a simpler version would be appreciated.
Basically, I am trying to join two objects title and content. So please help me to fix this.
const output = [{
"title": "Lorem Ipsum Test Title 1"
},
{
"content": "The short answer to this is yes."
},
{
"title": "Lorem Ipsum Test Title 2"
},
{
"content": "The short answer to this is yes."
},
{
"title": "Lorem Ipsum Test Title 3"
},
{
"content": "The short answer to this is yes."
},
{
"title": "Lorem Ipsum Test Title 4"
},
{
"content": "The short answer to this is yes."
}
];;
let start = 0;
let end = 2;
const finalOutput = [];
for (j = 0; j <= output.length; j++) {
const data = output.splice(start, end);
if (typeof data[0] != 'undefined') {
finalOutput.push({
title: data[0].title,
content: data[1].content
});
}
start = start + 2;
end = end + 2;
}
console.log(finalOutput)
The final output from the above code is below. It skips two objects.
