1

I have the following javascript object

const items = {   
   "item 1":{name:'test',vals:[{name:'first',....}]},
   "item 2":{name:'test3',vals:[{name:'second', ....}]}
    //other keys
 }

The object keys are dynamic and not just "item 1" and 2 and they keep on changing. I want to access the name property of each object. SO i have done the following by am stuck

Object.keys(items).forEach(key=>{
  let keyitem = items.key //am stuck on how to pass the key
 })

How do i proceed to the dynamic key as the items.key is undefined as there is no such key in the items object.How do i proceed.

Geoff
  • 6,277
  • 23
  • 87
  • 197
  • 3
    `items[key]` is the syntax you're looking for. – Thomas Oct 17 '19 at 15:03
  • 1
    You could also use Object.entries to get access to the key and value simultaneously: `for (const [key, item] of Object.entries(items)) { ... }`or `Object.entries(items).forEach(([key, item] => ...)` – Christian C. Salvadó Oct 17 '19 at 15:11

1 Answers1

3

Replace items.key as items[key]

Object.keys(items).forEach(key=>{
  let keyitem = items[key]
 })
chans
  • 5,104
  • 16
  • 43