简体   繁体   中英

How to loop array of objects if key is dynamic in array of objects in javascript

I want to access all values of an array of objects

let data = [
    { firstName1: 'a',  id: 1, email1: 'a@gmail.com'},
    { firstName2: 'b',  id: 2,  email2: 'b@gmail.com'}
  ];

 data.map(ele=> <p>{ ele.firstName}</p>)

result should be:

a
b

Accessing keys dynamically

let data = [
    { firstName1: 'a',  id: 1, email1: 'a@gmail.com'},
    { firstName2: 'b',  id: 2,  email2: 'b@gmail.com'}
 ];

Object.keys(data).map(key => <p>{data[key]}</p>)

There are multiple ways to extract key/value from objects in javascript

data.forEach( dataEle =>{  
  for (const [key, value] of Object.entries(dataEle)) {
    console.log(key +": "+ value)
  } 
})

Or another way like this

data.forEach( dataEle =>{   
  Object.keys(dataEle).forEach(key =>{
     console.log(key +": "+ dataEle[key])
  })
})

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM