1

This might be a basic question, but please have some patience as I have little experience working with JSON. I am accessing data from a web API that is returned in this format:

{
  "foo": {
    "data1": "this is unique data!",
    "data2": "this is also unique data!",
    "data3": {
      "info": "information!"
    }
  },
  "bar": {
    "data1": "this is unique data!",
    "data2": "this is also unique data!",
    "data3": {
      "info": "information!"
    }
  },
  "baz": {
    "data1": "this is unique data!",
    "data2": "this is also unique data!",
    "data3": {
      "info": "information!"
    }
  }
}

Without knowing what the foobar values are, would I be able to access the data within them all and return them like this?

[foo, bar, baz]

And if so, how? Thanks in advance.

2 Answers2

1

You can use Object.values

let response = {
  "foo": {
    "data1": "this is unique data!",
    "data2": "this is also unique data!",
    "data3": {
      "info": "information!"
    }
  },
  "bar": {
    "data1": "this is unique data!",
    "data2": "this is also unique data!",
    "data3": {
      "info": "information!"
    }
  },
  "baz": {
    "data1": "this is unique data!",
    "data2": "this is also unique data!",
    "data3": {
      "info": "information!"
    }
  }
}
console.log(Object.values(response));
// alternatively you can also use for..in

let arr = [];

for (let keys in response) {
  arr.push(response[keys])
}

console.log(arr);
brk
  • 48,835
  • 10
  • 56
  • 78
0

You could use Object.entries and then map over the entries if you want to keep the key in your array of objects.

const response = {
  "foo": {
    "data1": "this is unique data!",
    "data2": "this is also unique data!",
    "data3": {
      "info": "information!"
    }
  },
  "bar": {
    "data1": "this is unique data!",
    "data2": "this is also unique data!",
    "data3": {
      "info": "information!"
    }
  },
  "baz": {
    "data1": "this is unique data!",
    "data2": "this is also unique data!",
    "data3": {
      "info": "information!"
    }
  }
}

const arrayOfObjects = Object.entries(response)
  .map(([key, value]) => ({
    [key]: value
  }))

console.log(arrayOfObjects)
Freddy
  • 1,229
  • 2
  • 13
  • 22