如何在对象内循环对象并获取它的所有属性?

时间:2017-02-19 16:03:15

标签: javascript

我遇到了一些基本的javaScript。我正在尝试遍历一个对象并获取其所有属性。在我的示例对象中有一个对象文字,我无法访问其属性。就我而言,我想使用循环

访问“desc”及其属性

代码:

<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]);
   }

5 个答案:

答案 0 :(得分:1)

你是否尝试过这样做。只需循环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]);
   }

答案 1 :(得分:1)

您可以使用递归来迭代对象的所有键。在内部检查是否有对象并再次为实际对象调用iter。否则输出。

&#13;
&#13;
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);
&#13;
&#13;
&#13;

答案 2 :(得分:0)

只需一行:

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

&#13;
&#13;
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 />'))


*/
&#13;
&#13;
&#13;

答案 3 :(得分:0)

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>

答案 4 :(得分:0)

你可以使用普通的旧javascript来遍历&#39; desc&#39;键

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]);
};