Getting the first array from a fetch promise is a process that involves accessing the

When working with a fetch promise, I need to return a JSON object that contains all of my data. The challenge is that I am not sure what the object name will be. What I do know is that there will always be one object present.

Below is an example of my code where I am able to retrieve the necessary data when I know the object name (in this case, "foo"):

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

The response I expect would resemble this:

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

However, if the response looks like this:

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

My code would fail. How can I modify my code to ensure it will work regardless of the object name?

Answer №1

Utilize Object.values:

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

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

The code above makes use of destructuring, which is a shortcut for the following:

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

Previous syntax:

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

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

Answer №2

If you want to access the first element of an object, you can utilize Object.values().

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

For a more concise method, you can employ Array Destructuring.

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The never-ending nightmare of acquiring a Facebook Graph token

One of the tasks I regularly undertake for clients is fetching Facebook photos to incorporate into their websites. However, I often encounter a frustrating issue where the photos work for a while and then suddenly stop working. After doing some research o ...

Can a Stylus and Node.js with Express project utilize a local image?

Let's talk about using images in a Web app. In my Stylus file, style.styl, I typically set the image using code like this: .background background: url(http://path/to/image) But what if we want to save the image to our local app directory and use ...

JavaScript - Issue with retrieving object properties accurately

Here is a code snippet that I am working with: function retrieveObjects(name, data) { return data.filter(function(d) { return name.title == d.title; }).map(function(d) { return { "title": d.title, "sort": d. ...

Send an ArrayList to jQuery Flot

Good day. Apologies for any language barriers as English is not my first language. I am a novice in [see tags] and I have a web application that gathers a date and a serial number to execute a SQL query. The query returns some data (measurement values an ...

When using jQuery's `.click()` method on an element to collapse it with the 'show' parameter set to false, the disabling action will only take effect after the document

When you first run the program and click anywhere on the body, it activates the collapse element. I want it to only collapse the accordion on click, not show it immediately. Currently, it will deactivate only after it is hidden once. HTML <!DOCTYPE ht ...

Decoding Azure JSON Responses with C#

Check out the JSON Response displayed below: [ { "faceRectangle": { "top": 214, "left": 472, "width": 450, "height": 450 }, "faceAttributes": { "age": 19.0, "emotion": { "anger": 0.0, "contempt": 0.0, ...

converting a JSON string into an object using C#

I've spent a whole day scratching my head and searching on Google for a solution on how to convert a JSON string into an object. Here is the JSON data: { "statusCode": 200, "data": { "items": [ { "id": 2623, "JsonData": "{\"Number\":143,&b ...

Sending a multitude of variables using strings, evaluating them through various functions, and incorporating a variety of methods

To put it simply, my goal is to utilize an object literal that allows me to pass an unknown quantity of variables in any order to a function. While this may seem straightforward in principle, within my code, this object literal is passed to a second functi ...

When integrating react-hook-form with Material-UI TextField in a form, an error occurs stating that "TypeError: e.target is undefined" when

Hey there, I stumbled upon something fascinating and could really use some assistance. Every time I attempt to perform an onChange, I run into the following error: TypeError: e.target is undefined. Here's a snippet of my setup: import React, { useE ...

Neglecting the error message for type assignment in the Typescript compiler

Presented here is a scenario I am facing: const customer = new Customer(); let customerViewModel = new CustomerLayoutViewModel(); customerViewModel = customer; Despite both Customer and CustomerLayoutViewModel being identical at the moment, there is no ...

Output the JSON string retrieved from a specified URL

I'm currently working on using ajax to retrieve and parse JSON data from a specific URL. I am looking for assistance on how to store the parsed array into a variable. Any guidance or suggestions would be greatly appreciated. Thank you! function rvOff ...

Display the changing value at the beginning of the drop-down menu

I'm currently working on an AngularJS forEach loop where I need to display a dropdown list with dynamic values. The goal is to have the value stored in $scope.showCurrentProgram as the first selected element in the dropdown list when the page loads, a ...

"Experience the power of Angular.js through seamless animations created by blending the capabilities

I want to smoothly fade out the old view and fade in the new view. The challenge is that the new content must be positioned absolutely until the old one fades out. I also want to set a specific top position and height for the new content, but when I try to ...

Can assigning "NSMutableArray" to "NSArray" result in incompatible pointer types?

Here is some code that I wrote: NSMutableArray * reversedNamesArray; // There are already a lot of variables stored in here, this is just for documentation purposes reversedNamesArray = [reversedNamesArray sortedArrayUsingSelector:@selector(localizedCase ...

Animate a box moving continuously from the right to the left using jQuery

I'm trying to create a continuous motion where a box moves right, then left, and repeats the cycle. However, I can only get it to complete one cycle. $(document).ready(function() { function moveBox() { $('#foo').css({ 'ri ...

Encounter issue with async function in produce using Immer

Having an issue while attempting to create an asynchronous produce with immer. When calling the async function, this error is encountered: Below is my code snippet: import { combineReducers, createStore } from 'redux'; import produce from ' ...

Retrieve an array from a JSON file obtained from a web request using Python

I am looking to retrieve real-time quotes from a particular page using Python 3. You can find the page here. The quotes are stored in a JSON file within an array called "JsonData". My goal is to access the value stored in LTP within this JSON file. from ...

Showing the image as a backdrop while scrolling through text

How can I create an effect that continuously displays the image while scrolling text in Internet Explorer without using position: sticky or position: fixed? var sticky = document.querySelector('.sticky-container'); var img = document.querySele ...

Skipping beforeRouteLeave in VueJS

In my Vue SPA, there is a component where I am using the beforeRouteLeave guard to prevent accidental page exits. However, within this component, I occasionally make an ajax request that, upon successful completion, needs to redirect the user to another lo ...

What is the method for retrieving the hashed classname set by CSS Modules within a functional react component?

I am facing an issue with targeting a class named "nav" using querySelector because CSS modules hash the class name, turning it into something like nav-xyzxyz. Making it more complex, I have to verify if a class exists on an element with the class "nav", ...