Assuming I have an object array:
array=[
{
"Item": "A"
"Quantity" : 2
},
{
"Item": "B"
"Quantity" : 7
},
{
"Item": "C"
"Quantity" : 1
}
]
I am wondering what would be my options to get the following string output :
(A, 2), (B, 7), (C,1)
You could map the Object.values and join like this:
mapObject.values(a) returns an array like this: ["A", 2]join them using and wrap a () around using template literals map using another joinconst array = [
{
"Item": "A",
"Quantity" : 2
},
{
"Item": "B",
"Quantity" : 7
},
{
"Item": "C",
"Quantity" : 1
}
]
const str = array.map(a => `(${ Object.values(a).join(", ") })`)
.join(", ")
console.log(str)
If you're okay with (A,2), (B,7), (C,1) without a space in between them,
you could simply use
const array=[{"Item":"A","Quantity":2},{"Item":"B","Quantity":7},{"Item":"C","Quantity":1}]
const str = array.map(a => `(${ Object.values(a) })`).join(", ")
console.log(str)
This is not the most elegant way to do this but it's easy to understand:
array = [{
"Item": "A",
"Quantity": 2
},
{
"Item": "B",
"Quantity": 7
},
{
"Item": "C",
"Quantity": 1
}
];
var str = "";
for (var a = 0; a < array.length; a++) {
str += "(";
str += array[a].Item + ",";
str += array[a].Quantity + ")";
if (a != array.length - 1) {
str += ",";
}
}
console.log(str);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With