Home > database >  JavaScript loop through array of Object
JavaScript loop through array of Object

Time:10-27

I have this array of object:

let obj =  [ 
    { "id_feed": 114, "date_upd": 1666808102 },
    { "id_feed": 115, "date_upd": 1666808102 },
    { "id_feed": 116, "date_upd": 1666808102 },
] ;

I want to get all the keys and value. Note: this keys can dynamic, it could be anything.

So to get this I am trying :

Object.keys( obj ).forEach( ( item ) => {
    console.log( obj[item] )
})

But seems like doing wrong :(

Expected Output:

id_feed  = 114
date_upd = 1666808102
id_feed  = 115
date_upd = 1666808102
id_feed  = 116
date_upd = 1666808102

CodePudding user response:

Using Object.keys() can also do it

let obj =  [ 
    { "id_feed1": 114, "date_upd": 1666808102 },
    { "id_feed2": 115, "date_upd": 1666808103 },
    { "id_feed3": 116, "date_upd": 1666808104 }
] 

obj.forEach(d1 => {
  Object.keys(d1).forEach(d2 => {
    console.log(d2   ' = '   d1[d2])
  })
})

CodePudding user response:

Use Object.entries:

let obj =  [ 
    { "id_feed": 114, "date_upd": 1666808102 },
    { "id_feed": 115, "date_upd": 1666808102 },
    { "id_feed": 116, "date_upd": 1666808102 },
];

obj.forEach(item => {
  Object.entries(item).forEach(([key, value]) => {
    console.log(key, "=", value)
  })
})

CodePudding user response:

Here is my solution:

let obj =  [ 
    { "id_feed": 114, "date_upd": 1666808102 },
    { "id_feed": 115, "date_upd": 1666808102 },
    { "id_feed": 116, "date_upd": 1666808102 },
] ;

obj.forEach(o=>{
    console.log("id_feed=" o.id_feed);
  console.log("date_upd=" o.date_upd);
})

  • Related