Reputation: 485
I have an array of objects such as:
const array = [<Button>abc</Button>, <Button>def</Button>]
where when I render them with:
return array
I get a list of buttons next to each other.
something similar to the top line of this example picture:
However I want to join the buttons so it look like the bottom line. I tried to use array.join("+")
but that no longer rendered buttons instead rendering <object object>+<object object>
Is it possible to do this? keep in mind the array needs to be looped to include all items and ideally it knows not to add a +
to the last element.
Upvotes: 0
Views: 87
Reputation: 379
Try This
var btns = document.querySelectorAll("button");
var btnArray = [], btnString = "";
btns.forEach(curr => {
btnArray.push(curr);
});
btnArray.forEach(curr =>{
btnString += curr.innerText + "+";
});
btnString = btnString.substring(0, btnString.length - 1);
console.log(btnString);
A simpler method using join() would look like this
var btns = document.querySelectorAll("button");
var btnArray = [], btnText = [], btnString = "";
btns.forEach(curr => {
btnArray.push(curr);
});
btnArray.forEach(curr =>{
btnText.push(curr.innerText);
});
btnString = btnText.join(" + ");
console.log(btnString);
Upvotes: 0
Reputation: 5473
Its a tricky use-case. I was able to achieve writing conditional inside map function.
{array.map((item, index) => {
if (index === array.length - 1) {
return item;
}
return [item, "+"];
})}
Here's working example link: https://stackblitz.com/edit/react-hceymc
Upvotes: 1