-1

I have JSON data in another file, I am accessing that from a module file. I am using a loop to get lots of data easily but I am stuck on a problem. When using dot notation it goes cars.c1.name, but in my example it is cars.c+i+.. and then it stops because I don't know how to add .name to that.

This is for a test project, I have tried googling but it is a particular issue.

Snippet of the JSON:

"c1": {
            "id": 1,
            "name": "Sprinter Boxtruck",
            "make": "Mercedes",
            "price": "£500,000",
            "topspeed": "87mph",
            "vip": "false"
        },

The constant in question:

const carName = cars.c+i+.name; // not working

i is the constant with which I am using the loop.

Expected result would be for me to have 4 different objects, actual - There is no error thrown but it doesn't work.

tzcoding
  • 69
  • 6

3 Answers3

3

here is what's wrong with what you are doing:

const carName = cars.c+i+.name; // not working

to fetch a json value by key, you need to specify the key in square brackets. cars is the JSON object and key would be "c1", "c2", "c3" etc. Also you are trying to fetch multiple values, the key format would be "c" + i.

const carName = cars["c"+ i].name;

the above line of code shows how you can fetch your JSON value correctly.

Rahul Vala
  • 695
  • 8
  • 17
  • 1
    While this command may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value – LordWilmore May 13 '19 at 20:58
1

You need to use the bracket notation here:

cars[`c${i}`].name

Basically, the c${i} is creating the variable name c1, c2, c3, etc.

Update Thanks to @stevendesu, some browsers may not support the back-tick operator. So here is the same answer using string concat:

cars["c" + i].name
Kousha
  • 32,871
  • 51
  • 172
  • 296
  • 2
    Depending on the browsers they need to support, they may not be in an environment that supports the back-tick operator for string interpolation yet. You should also mention `cars["c" + i]` as an option – stevendesu May 13 '19 at 19:51
1

This will do what you're looking for:

var cars = {
  "c1": {
    "id": 1,
    "name": "Sprinter Boxtruck",
    "make": "Mercedes",
    "price": "£500,000",
    "topspeed": "87mph",
    "vip": "false"
  }
};

var i = 1;
var carName = cars['c' + i].name;

console.log(carName);
John
  • 577
  • 4
  • 20