DanielJ
DanielJ

Reputation: 769

How to get first array in fetch promise

I need to return in my fetch promise a JSON object which contains all my data. The issue is I don't know what the object name is. What I do know is that there will always be one object.

Here is me example code where I get what I need knowing the object name (in this case foo

  return fetch(endPoint)
    .then(res => res.json())
    .then(res => res.foo)
    .then(res => console.log(res))

My response would look like this

{
    "foo": [
        "bar1",
        "bar2",
        "bar3"
    ]
}

However my code would fail if this was the response:

{
    "goo": [
        "bar1",
        "bar2",
        "bar3"
    ]
}

How can I ensure my code always works no matter what the object is called?

Upvotes: 1

Views: 378

Answers (2)

Maheer Ali
Maheer Ali

Reputation: 36564

You can use Object.values() and access its first element.

const obj = {"foo": ["bar1","bar2", "bar3"]}
const res = Object.values(obj)[0]
console.log(res)

You can make it even shorter using Array Destructuring

const obj = {"foo": ["bar1","bar2", "bar3"]}
const [res] = Object.values(obj)
console.log(res)

Upvotes: 0

Jack Bashford
Jack Bashford

Reputation: 44107

Use Object.values:

const obj = {
  "foo": [
    "bar1",
    "bar2",
    "bar3"
  ]
};

const [foo] = Object.values(obj);
console.log(foo);

The above uses destructuring, and it's shorthand for this:

const foo = Object.values(obj)[0];

Older syntax:

var obj = {
    "foo": [
        "bar1",
        "bar2",
        "bar3"
    ]
};

var foo = obj[Object.keys(obj)[0]];
console.log(foo);

Upvotes: 1

Related Questions