Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript object array to string

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)
like image 606
Kev Avatar asked Dec 31 '25 07:12

Kev


2 Answers

You could map the Object.values and join like this:

  • Loop through the array using map
  • Object.values(a) returns an array like this: ["A", 2]
  • join them using and wrap a () around using template literals
  • join the resulting string array from map using another join

const 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)
like image 179
adiga Avatar answered Jan 03 '26 12:01

adiga


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);
like image 45
obscure Avatar answered Jan 03 '26 10:01

obscure



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!