0

So I have to get the first object of this list:

{
"2489": {
    "status": {
        "idstatus": "3",
        "status": "Sold"
    }
},

"2490": {
    "status": {
        "idstatus": "3",
        "status": "Sold"
    }
}

}

I don't know beforehand the IDs ['2489'] and ['2490']. Sometimes it responses only one of these IDs, sometimes 3 or more.

How can I get like ['2490'].status.idstatus without knowing ['2490']?

  • Does this answer your question? [Get array of object's keys](https://stackoverflow.com/questions/8763125/get-array-of-objects-keys) – gre_gor May 27 '22 at 08:56

2 Answers2

1

There are several ways to do this. If you're running a modern JS environment, you can use Object.keys or Object.values.

Assuming your JSON response object is a variable named res, you can construct a dynamic array of IDs like this:

const ids = Object.keys(res) // ["2489", "2490", ...]

If you don't care about the IDs at all and want an array of all the inner objects, try this:

const items = Object.values(res) // [ { "status" : ... }, ... ]
glhrmv
  • 1,712
  • 1
  • 16
  • 23
1

you can do it using Object.values and map or if you need the key you can use Object.entries

const data = {
"2489": {
    "status": {
        "idstatus": "3",
        "status": "Sold"
    }
},

"2490": {
    "status": {
        "idstatus": "3",
        "status": "Sold"
    }
}
}

const statusIds = Object.values(data).map(d => d.status.idstatus)
console.log(statusIds)

const statusIdAndKey = Object.entries(data).map(([k, d]) => [k, d.status.idstatus])
console.log(statusIdAndKey)
R4ncid
  • 6,944
  • 1
  • 4
  • 18