0

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
5
  • It's just obj.forEach(...). Commented Oct 27, 2022 at 3:02
  • 1
    What's your expected output? Commented Oct 27, 2022 at 3:05
  • @bbbbbbbboat I have updated. Commented Oct 27, 2022 at 3:07
  • Well, in Object.keys( obj ), obj is not an object, but an array. Commented Oct 27, 2022 at 3:08
  • The definition of obj in the question indicates that obj is an Array (the naming seems to be counter-intuitive to the value). So, please try: console.log(...obj?.flatMap(ob => Object.entries(ob)?.map(([k, v]) => `${k} = ${v}`))); Commented Oct 27, 2022 at 3:13

3 Answers 3

1

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])
  })
})

Sign up to request clarification or add additional context in comments.

2 Comments

@Shibbir I would advice your to accept Amila's answer,seems more elegant and answered more earlier
But both are same answer.
1

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)
  })
})

Comments

0

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);
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.