我如何获取嵌套对象的键=用于...。

时间:2018-10-29 10:10:17

标签: javascript object

这是我的代码。如何使用let output = input.map( item => { return ({ID:item[0],name:item[1],birthDay:item[2]+item[3],hobby:item[4]}) }) 循环获得key对中的key-value

for

所需的输出如下:

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

请帮助

5 个答案:

答案 0 :(得分:1)

var getKeys = function(obj) {
  var keys = [];
  Object.keys(obj).forEach(function(key){
    keys.push(key);
    if(typeof obj[key] == 'object'){
      keys = keys.concat(getKeys(obj[key]));
    }
  })
  return keys;
}

然后

var keys = getKeys(apartment);

答案 1 :(得分:1)

您可以使用一个简单的正则表达式,如下所示:

Error: no key found

答案 2 :(得分:1)

我们可以通过使用正则表达式,转换对象字符串并应用正则表达式来轻松提取特定单词来轻松完成

运行所需输出的代码段

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

apartment = JSON.stringify(apartment);

var re = /(")\w+(")(:)/g;
var match;
do {
    match = re.exec(apartment);
    if (match) {
        console.log(match[0]);
    }
} while (match);

  

regex:/(“)\ w +(”)(:)/ g

仅提取更多click here的密钥

执行while循环以检测字符串中的多个匹配项

答案 3 :(得分:0)

var inputs = [
  {a:1,b:2,c:3}, // Simple object
  {a:{b:2,c:3}}, // Simple object with nesting
  {a:{a:{b:2,c:3}}}, // Repeated key hiding nesting
  {a:[{b:2,c:3}]}, // keys behind array
];
inputs.push(inputs); // reference cycle and array at top

function getKeys(obj) {
  var all = {};
  var seen = [];
  checkValue(obj);
  return Object.keys(all);

  function checkValue(value) {
    if (Array.isArray(value)) return checkArray(value);
    if (value instanceof Object) return checkObject(value);
  }

  function checkArray(array) {
    if (seen.indexOf(array) >= 0) return;
    seen.push(array);
    for (var i = 0, l = array.length; i < l; i++) {
      checkValue(array[i]);
    }
 }

  function checkObject(obj) {
    if (seen.indexOf(obj) >= 0) return;
    seen.push(obj);
    var keys = Object.keys(obj);
    for (var i = 0, l = keys.length; i < l; i++) {
      var key = keys[i];
      all[key] = true;
      checkValue(obj[key]);
    }
  }
}

var result = inputs.map(getKeys);

console.log(result);

答案 4 :(得分:0)

您可以使用递归函数:

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"]