即使对象中存在另一个数组,如何获取数组键名?

时间:2019-01-26 14:31:52

标签: arrays json reactjs

即使数组中存在另一个数组,我也试图将数组键名添加到新数组中。

到目前为止,我能够获得所有密钥名称,但密钥名称在下一层。

我有现有的数组:

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

仍未达到预期。完全相同的结果

1 个答案:

答案 0 :(得分:1)

@NikKyriakides评论解决了所有问题。答案是这个问题: Get all keys of a deep object in Javascript