-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?

karthik_personal
  • 369
  • 1
  • 3
  • 14
  • 1
    `alreadyCachedData[0].hasOwnProperty(key) == "id"` will never be true, `hasOwnProperty` returns a boolean. Neither `true` nor `false` is ever `== "id"`. – T.J. Crowder Jan 26 '22 at 18:19
  • What is `alreadyCachedData`? What does `alreadyCachedData[0].hasOwnProperty(key)` return? – mykaf Jan 26 '22 at 18:20

1 Answers1

4

it's easy with Array.map

const out = alreadyCachedData.map(o => o.id)
Micael Levi
  • 5,054
  • 2
  • 16
  • 27