-4

I have the following JSON that I am trying to parse:

{
    "brands": [
        {
            "_id": "46378Bkjdd",
            "result": {
                "car": {
                    "Name": [
                        "mercedes",
                        "bmw",
                        "golf",
                        "seat"
                    ]
                }
            }
        },
        {
            "_id": "cf876567",
            "result": {
                "car": {
                    "Name": [
                        "renault",
                        "porsh"
                    ]
                }
            }
        }
    ]
}

Need to get the "Name" with : mercredes, bmw, golf, seat, renault, porsh The size could be more thant 2 "_id", this is just for the example.

I tried this but it doesn't work:

for (var i=0; response.brands.length; i++){
   console.log("Names: "+response.brands.result.car.Name[i]);
}

Thanks

Carlos
  • 79
  • 1
  • 4
  • 16

3 Answers3

1

You need to loop over the Name array. In addition brands is an array. Your loop needed something like i < array.length to get going, but it never did. Here's one that works. It caches the array length in the loop (in l) which is considered good practice.

var array = obj.brands[0].result.car.Name;
for (var i = 0, l = array.length; i < l; i++) {
  console.log('Name: ' + array[i])
}

DEMO

Andy
  • 61,948
  • 13
  • 68
  • 95
0

To iterate over all given subarrays you should use two for loops as follows:

var brandsLen = a.brands.length;
for (j = 0; j < brandsLen; ++j) {
    var singleBrandLen = a.brands[j].result.car.Name.length;
    for (i = 0; i < singleBrandLen; ++i) {
        console.log(a.brands[j].result.car.Name[j]);
    }
}

a is your input array.

marian0
  • 3,336
  • 3
  • 27
  • 37
0

A functional approach, without loops:

var result = obj.brands.reduce(function (a, b) {
  return a.concat(b.result.car.Name);
}, []);
console.log(result);

Outputs:

["mercedes", "bmw", "golf", "seat", "renault", "porsh"]
chris-l
  • 2,802
  • 1
  • 18
  • 18