Nag
Nag

Reputation: 956

How do you loop over object inside an object and get all it's properties?

I am stuck with some basic javaScript. I'm trying to loop over an object and get all its properties. In my example object has one more object literal inside of it, and I am unable to access its properties. In my case, I wanted to access "desc" and its properties using loop

code:

<script type="text/javascript">
    var car = {
        make: "volkswagen",
        year: 2001,
        desc: {
            brand: "audi",
            name: "R6",
            price: "45L"
        }
   }

   for (var i in car) {
       document.write("<br>" + car[i]);
   }

Upvotes: 0

Views: 55

Answers (5)

Abdennour TOUMI
Abdennour TOUMI

Reputation: 93253

Just one line :

Array.prototype.concat(...Object.keys(car).map(k => typeof car[k] === 'object' ? Object.values(car[k]) : car[k] )).forEach(value => document.write(value + '<br />'))

const car = {
  make: "volkswagen",
  year: 2001,
  desc: {
    brand: "audi",
    name: "R6",
    price: "45L"
  }
};

Array.prototype.concat( // flatten array
  ...Object.keys(car)
       .map(k => typeof car[k] === 'object' ? Object.values(car[k]) : car[k] ))
       .forEach( value => document.write(value + '<br />') 
);

/*


//--For more readable code , you can split the code to 3 instructions : 

const vals =(obj) => flatten(Object.keys(obj).map(k => typeof obj[k] !== 'object' ? obj[k] : vals(obj[k]))) ; 

const flatten = arr => arr.reduce((acc, val) => acc.concat(Array.isArray(val) ? flatten(val) : val), []);

//--then 

vals(car).forEach(leaf => document.write(leaf + '<br />'))


*/


Upvotes: 0

grizzthedj
grizzthedj

Reputation: 7505

You can just use plain old javascript to iterate through the 'desc' keys

var car = {
    make: "volkswagen",
    year: 2001,
    desc: {
        brand: "audi",
        name: "R6",
        price: "45L"
    }
}

for (var key in car['desc']) {
  console.log("KEY: " + key);
  console.log("VALUE: " + car['desc'][key]);
};

Upvotes: 0

ibrahim mahrir
ibrahim mahrir

Reputation: 31692

function showObject(object) {                   // take an object and return an ul element
  var ul = document.createElement("ul");        // the ul element
  for (var key in object) {                     // for each key in object
    var li = document.createElement("li");      // create a li element
    li.textContent = key + ": ";                // set its text to the "key: "
    if (typeof object[key] == "object")         // if the value of this key is also an object, then call showbject on that sub-object (read about recursion)
      li.appendChild(showObject(object[key]));  // add the sub-ul to the li element
    else                                        // if it's not a sub-object
      li.textContent += object[key];            // then append its value to the text of the li element ("key: value")
    ul.appendChild(li);                         // add the li to the parent ul
  }
  return ul;                                    // return the ul element
}

var car = {
  make: "volkswagen",
  year: 2001,
  desc: {
    brand: "audi",
    name: "R6",
    price: "45L"
  }
}

var ul = showObject(car);                             // get the ul of this object
document.getElementById("container").appendChild(ul); // append it to the div
<div id="container"></div>

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386654

You could use a recursion which iterates over all keys of the object. Inside check if you got an object and call iter again for the actual object. Otherwise make an output.

function iter(object) {
    Object.keys(object).forEach(function (k) {
        if (object[k] && typeof object[k] === 'object') {
            iter(object[k]);
            return;
        }
        document.body.appendChild(document.createTextNode(k + ': ' + object[k])); 
        document.body.appendChild(document.createElement('br')); 
    });
}

var car = { make: "volkswagen", year: 2001, desc: { brand:"audi", name:"R6", price:"45L" } };
iter(car);

Upvotes: 1

Hikmat Sijapati
Hikmat Sijapati

Reputation: 6994

Did you try like this.Just loop over car['desc'].

var car = {
        make: "volkswagen",
        year: 2001,
        desc: {
            brand: "audi",
            name: "R6",
            price: "45L"
        }
   }

   for (var i in car['desc']) {
       document.write("<br>" + car['desc'][i]);
   }

Upvotes: 1

Related Questions