I'm working on a project, where I have to get data from an API. After the data request, the response data had a structure like this:
Data: [
{s:1, d:2, f:3},
{s:3, d:1, f:2},
{s:2, d:3, f:1}
];
My problem is, I want to iterate through each object in Data
and display it's properties and values.
Have tried using Object.(keys, entries)
but they only make matters worse(maybe because, I don't really understand how they work).
Assuming Data
is an array (you made a mistake and used curly braces), it is an array of objects. You need to "reach inside" into each array entry and call Object.entries
on it. Object.entries
turns each key-pair value into a key pair tuple.
const entries = Data.map(entry => Object.entries(entry))
// [
// ['s', 1], ['d', 2], ['f', 3],
// and so on
// ]
I corrected the data-array to a valid JS-datastructure, I hope you mean this.
Iterate with forEach over the objects from your array. Get with Object.entries the key/value-pairs from the object and print both in second forEach .
let data= [ {s:1, d:2, f:3}, {s:3, d:1, f:2}, {s:2, d:3, f:1} ]; data.forEach(obj => { Object.entries(obj).forEach(([key,value]) => { console.log('Key: ' + key + ' Value: ' + value); }) })
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.