I try to merge an array of objects into a single string, but got a bit lost. The input looks like that:
const array = [
{
key: "title",
text: " Example Text title",
},
{
key: "description",
text: "Example Text description",
},
{
key: "video",
text: "Example Text video",
},
];
Expected Output:
"title: Example Text title, description: Example Text description, video: Example Text video"
Thanks for any hint.
>Solution :
Since you want a single string out of this, and not an array, you will want to use Array.forEach to concatenate onto an existing string object, like so:
let outStr = '';
array.forEach((ele, idx) =>
outStr += `${ele.key}: ${ele.text}${idx < array.length ? '' : ', '}`
);
You could also use Array.map like the folks in the comments above suggested, but you will need to join the result to produce a single string at the end.