-3

I have following object structure, and

[
  { id: 183, firstName: 'first0', lastName: 'last0', std: 0 },
  { id: 184, firstName: 'first1', lastName: 'last1', std: 1 },
  { id: 185, firstName: 'first2', lastName: 'last2', std: 2 }
]

I want to iterate through the object and get [183,184,185]. Here is what I have tried

alreadyCachedData = [
  { id: 183, firstName: 'first0', lastName: 'last0', std: 0 },
  { id: 184, firstName: 'first1', lastName: 'last1', std: 1 },
  { id: 185, firstName: 'first2', lastName: 'last2', std: 2 }
]
for (var key in alreadyCachedData[0]) {
  if (alreadyCachedData[0].hasOwnProperty(key)  == "id") {
    var val = alreadyCachedData[0][key];
    console.log(val);
  }
} 

But I don't get required result, any help?

2
  • 1
    alreadyCachedData[0].hasOwnProperty(key) == "id" will never be true, hasOwnProperty returns a boolean. Neither true nor false is ever == "id". Commented Jan 26, 2022 at 18:19
  • What is alreadyCachedData? What does alreadyCachedData[0].hasOwnProperty(key) return? Commented Jan 26, 2022 at 18:20

1 Answer 1

5

it's easy with Array.map

const out = alreadyCachedData.map(o => o.id)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.