这是我的代码。如何使用key循环获取key-value对中的for

var apartment = {
  bedroom: {
    area: 20,
    bed: {
      type: 'twin-bed',
      price: 100
    }
  }
};


所需的输出如下:

/* desired results :
 * bedroom
 * area
 * bed
 * type
 * price
*/


请帮忙

最佳答案

您可以使用递归函数:

function getKeys(source, dest) {
    for (let key in source) {
        if (typeof source[key] == 'object') {
            dest.push(key)
            getKeys(source[key], dest)
        } else {
            dest.push(key)
        }
    }
    return dest
}

result = []
const apartment = {
  bedroom: {
    area: 20,
    bed: {
      type: 'twin-bed',
      price: 100
    }
  }
}
getKeys(apartment, result) // ["bedroom", "area", "bed", "type", "price"]

09-25 19:21