1

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?

2 Answers 2

1

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);

Sign up to request clarification or add additional context in comments.

3 Comments

you could also explain further, what you did there, maybe OP doesn't understand what destructuring is. (not the down voter)
Oh whoops, my bad @MaheerAli, I'll fix that.
Fixed now @MaheerAli, any better?
0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.