即使数组中存在另一个数组,我也试图将数组键名添加到新数组中。
到目前为止,我能够获得所有密钥名称,但密钥名称在下一层。
我有现有的数组:
searchResult = [
{"id":1,
"name":"Duracell",
"manufacturer":"Duracell",
"model":"DC2400",
"type": {
"id":4,"type":"Nickel Metal Hydride","rechargeable":true
},
"size": {
"size":"AAA","shape":"Cylindrical"
},
"nominalCapacity":750,
"nominalVoltage":1,
"diameter":10,
"width":null,
"height":44,
"length":null,
"depth":null
},
{...},
{...}
]
我将其作为道具并获取键名:
const formFields = Object.keys(this.props.searchResult[0])
console.log(formFields)
console.log
的输出是:
["id",
"name",
"manufacturer",
"model",
"type",
"size",
"nominalCapacity",
"nominalVoltage",
"diameter",
"width",
"height",
"length",
"depth"]
缺少此内容
"type": {
"id", "type", "rechargeable"
},
"size": {
"size","shape"
}
所以我希望它是这样的:
["id",
"name",
"manufacturer",
"model",
"type": {
"id", "type", "rechargeable"
},
"size": {
"size","shape"
},
"nominalCapacity",
"nominalVoltage",
"diameter",
"width",
"height",
"length",
"depth"]
更新 从下面包含this link的评论中,我使用了代码:
const formFields = this.props.searchResult[0]
var keys = [];
for(var key in formFields) {
keys.push(key);
if(typeof formFields[key] === "object") {
var subkeys = getDeepKeys(formFields[key]);
keys = keys.concat(subkeys.map(function(subkey) {
return key + "." + subkey;
}));
}
}
console.log(keys)
console.log
的输出是:
["id", "name", "manufacturer", "model", "type", "size", "nominalCapacity", "nominalVoltage", "diameter", "width", "height", "length", "depth"]
仍未达到预期。完全相同的结果