[英]Pushing keys and properties from object to array
I would like to push all properties and keys from objects, including nested ones. 我想从对象(包括嵌套对象)中推送所有属性和键。 That's how i'm trying:
我就是这样想的:
'use strict'; var getProps = function getProps(destination, object) { destination = destination || []; for (var key in object) { typeof object[key] === 'object' && object[key] !== 'null' ? destination.push(getProps(destination, object[key])) : destination.push(key); } return destination; } var object = { one: { two: 'three' } }; console.log(getProps([], object))
As you can see, isn't working properly. 如您所见,它无法正常工作。
Thanks in advance. 提前致谢。
UPDATE - 更新-
Desire output: 需求输出:
['one', 'two', 'three'];
You could use recursion to achieve your desired result. 您可以使用递归来达到所需的结果。
var object = { one: { two: 'three' }, four: { five: 'six', seven: [ 'eight', 'nine', 'ten' ], eleven: { twelve: { thirteen: { fourteen: 'fifteen' } } } } }; function rabbitHole(output, object) { for (var i in object) { if (!Array.isArray(object)) { output.push(i); } if (typeof object[i] == 'object') { rabbitHole(output, object[i]); } else { output.push(object[i]); } } return output; } var output = rabbitHole([], object); console.log(output);
You could use side-effects of JSON.stringify
to simplify your code. 您可以使用
JSON.stringify
的副作用来简化代码。
function keysAndVals(object) {
var result = [];
JSON.stringify(object, function(key, val) {
result.push(key);
if (typeof val !== "object") result.push(val);
return val;
});
return result;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.