Pedro Díaz Pedro Díaz - 21 days ago 4x
Javascript Question

Iterate through Object keys in Javascript

Having an object like this:

req.body = {
currency : "USD",
item_name_1: "something",
item_price_1: "something else",
item_name_2: "something",
item_price_2: "something else",
item_name_3: "something",
item_price_3: "something else",
address: "some address"
itemCount: 3

What is the best way to only get the key/value pairs of only item names??, I would try something like this but of course it doesn't work:

var cart= "";
for (var i=1; i<= req.body.itemCount;i++){
cart += req.body.item_name_+i+
" "+req.body.item_price_+i;

Thanks in advance!


If you want to grab a value from an Object based on a string literal, or a String, you'll need to use [] notation where the value between the [] is a string. You can build a string from string literals and variables via the + operator. Change your string concatenation to this:

cart += req.body["item_name_" + i] 
        + " " 
        + req.body["item_price_" + i];