Edgars Šusts
Edgars Šusts

Reputation: 111

How to get array key names even if in object there is another array?

I am trying to get array key names to new array even if there is another array in array.

So far I am able to get all key names except key names which ones are in one level down.

I have existing array:

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
   },
   {...},
   {...}
]

And I am getting it as props and getting key names:

const formFields = Object.keys(this.props.searchResult[0])
console.log(formFields)

console.log output is:

 ["id",
  "name",
  "manufacturer",
  "model",
  "type",
  "size",
  "nominalCapacity",
  "nominalVoltage",
  "diameter",
  "width",
  "height",
  "length",
  "depth"]

It is missing this:

   "type": {
     "id", "type", "rechargeable"
    },
     "size": {
       "size","shape"
    }

So im expecting it to be something like this:

 ["id",
  "name",
  "manufacturer",
  "model",
  "type": {
    "id", "type", "rechargeable"
   },
   "size": {
     "size","shape"
    },
  "nominalCapacity",
  "nominalVoltage",
  "diameter",
  "width",
  "height",
  "length",
  "depth"]

UPDATE From comment below which contains this link i used code:

 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 output is:

["id", "name", "manufacturer", "model", "type", "size", "nominalCapacity", "nominalVoltage", "diameter", "width", "height", "length", "depth"]

Still not what is expected. Totally same result

Upvotes: 0

Views: 58

Answers (1)

Edgars Šusts
Edgars Šusts

Reputation: 111

@NikKyriakides comment solved everything. Answer is in this question: Get all keys of a deep object in Javascript

Upvotes: 1

Related Questions