This one may have been answered in the past, but I seem to be having trouble iterating through a nested structure and cannot find anything that will point me in the right direction. Below is the object I am trying to parse.
const nestedArray =
{ id : 100
, interval : 1000
, enable : true
, topics:
[ { topic1:
[ { id: 0, 'error-code' : 100 }
, { id: 1, status : 200 }
, { id: 2, mode : 300 }
] }
, { topic2:
[ { id: 0, count : 100 }
, { id: 1, total : 200 }
, { id: 2, operation : 300 }
] } ] }
I want to iterate nestedArray and from topics extract the the topic name i.e."topic1" and the key (name) in the associated key-value properties in the nested array i.e. "id" and "error-code".
I am new to this and have tried Object.entries, Object.keys, Object.values and a recursive function etc but never get the values I need or error because the method cant be applied to the Object. I would appreciate some explanation regarding how this is achieved.
Something like that ?
const nestedArray =
{ id : 100
, interval : 1000
, enable : true
, topics:
[ { topic1:
[ { id: 0, 'error-code' : 100 }
, { id: 1, status : 200 }
, { id: 2, mode : 300 }
] }
, { topic2:
[ { id: 0, count : 100 }
, { id: 1, total : 200 }
, { id: 2, operation : 300 }
] } ] }
nestedArray.topics.forEach( topic =>
{
let key0 = Object.keys( topic)[0]
topic[key0].forEach(el =>
console.log( key0, '->', Object.keys(el). join(', ')))
})
console.log( '\notherwise :')
nestedArray.topics.forEach( topic =>
{
let key0 = Object.keys( topic)[0]
topic[key0].forEach(el =>
console.log( key0, '->', Object.entries(el).map(([k,v])=>`${k}: ${v} `).join(', ')))
})
.as-console-wrapper {max-height: 100%!important;top:0 }
.as-console-row::after { display:none !important; }