[英]javascript get object keys in array
I have an object similar to the one below:我有一个类似于下面的 object:
const obj = {
"test1": {
"test12": "val1",
"test13": {
"test131": "val1",
"test132": "val2"
}
},
"test2": "val2"
}
I want to receive the keys as follows:我想按如下方式接收密钥:
const keys = [["test1", "test12", "test13", "test131", "test132"], ["test2"]];
You can recursively process the entries in the object, collecting keys as you go and flattening the result arrays at all levels other than the top:您可以递归处理 object 中的条目,像您一样收集密钥 go 并将结果 arrays 在除顶部以外的所有级别展平:
const obj = { "test1": { "test12": "val1", "test13": { "test131": "val1", "test132": "val2" } }, "test2": null, "test3": { "test31": "val3" }, "test4": { "test41": [1, 2, 3, 4] } } const getKeys = (obj, flat = false) => { const keys = Object.entries(obj).map(([k, v]) => v instanceof Object &&?(v instanceof Array), [k. ..,getKeys(v: true)]? [k]) return flat. keys:flat(). keys } const allKeys = getKeys(obj) console.log(allKeys)
Here you go:这里是 go:
const obj = { "test1": { "test12": "val1", "test13": { "test131": "val1", "test132": "val2" } }, "test2": "val2" }; const mapToKeys = ([key, value]) => { if (Object.prototype.toString.call(value) === '[object Object]') { return [key, ...getKeys(value)]; } return [key]; }; const getKeys = (o) => Object.entries(o).flatMap(mapToKeys); const keys = Object.entries(obj).map(mapToKeys); console.log(keys);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.