Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Loop Through A Nested Object [duplicate]

Hi there i have an nested object that looks like this

var dogTypes = {
GermanShepard {color: "black and white"},
Beagle       {color: "brown and white"},
cheuwahwah  {color: "green and white"},
poodle:    {color: "purple and white"},
 }

im trying to loop through all the properties in a nested object i know how to do that with a regular object but not a nested one so if someone could help me that would be great.

 for (var key in dogTypes) {
 console.log(key + " : " + dogTypes[key])
 }

heres my code which prints out

 GreatDane : [object Object]
   GermanSheppard : [object Object]
   Beagle : [object Object]
   BullDog : [object Object]

where would i incorporate the color property in the for in loop please help!! thanks

like image 582
Sammy Avatar asked Aug 29 '17 23:08

Sammy


People also ask

How do I map a nested object?

How do I map a nested object in react JS? Use the map() method to iterate over the outer array. On each iteration, call the map() method on the nested array. Render the elements of the nested array.

What is nested object in JavaScript?

The basic definition of an object in JavaScript is a container for named values called properties (keys). Sometimes, we need to create an object inside another object. In this case, it's called a nested object.

How for in loop works in JavaScript?

A for loop repeats until a specified condition evaluates to false. The JavaScript for loop is similar to the Java and C for loop. When a for loop executes, the following occurs: The initializing expression initialExpression , if any, is executed.


1 Answers

"im trying to loop through all the properties in a nested object"

A nested object is a regular object. You just need a nested loop if you want to reach all properties in the nested objects.

var dogTypes = {
  GermanShepard: {
    color: "black and white"
  },
  Beagle: {
    color: "brown and white"
  },
  cheuwahwah: {
    color: "green and white"
  },
  poodle: {
    color: "purple and white"
  },
};

for (var key in dogTypes) {
  for (var key2 in dogTypes[key]) {
    console.log(key, key2, dogTypes[key][key2]);
  }
}

If there's only one, known key in the nested object, then you don't need a loop, but then you also don't really need a nested object.

like image 56
spanky Avatar answered Oct 02 '22 18:10

spanky