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.
CodePudding user response:
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.
CodePudding user response:
const array = [
{
key: "title",
text: " Example Text title",
},
{
key: "description",
text: "Example Text description",
},
{
key: "video",
text: "Example Text video",
},
];
let result = "";
array.forEach((object, index) => {
result = `${object.key}: ${object.text}`
if(index < array.length - 1) {
result = ', ';
}
});
console.log(result);
CodePudding user response:
I hope the following is useful for you.
const array = [
{
key: "title",
text: " Example Text title",
},
{
key: "description",
text: "Example Text description",
},
{
key: "video",
text: "Example Text video",
},
];
array.map(item => `title: ${item.text}, description: ${item.text}, video: ${item.text}`).toString()
//'title: Example Text title, description: Example Text title, video: Example Text title,title: Example Text description, description: Example Text description, video: Example Text description,title: Example Text video, description: Example Text video, video: Example Text video'