extracting key-value pairs from nested arrays in javascript objects

As a beginner in javascript, I am facing an issue that may seem basic to others. Here is the json data I am working with:

{
    "statusCode": 200,
    "status": "success",
    "data": [
        [
            {
                "city": "Alexandria",
                "country": "Egypt",

            },
            {
                "city": "Alexandria",
                "country": "Egypt",

            },]]

My goal is to access specific elements within this data:

0: {city: "Alexandria", country: "Egypt"}
1: {city: "Antalya", country: "Turkey"}

I have attempted the following code snippet:

getData = function (data) {
    keys = Object.keys(data[0]);
    data = [];
    keys.forEach(function (key) {
        data.push(key);
    });
    return data;
}

However, the output of this code is not what I expected. It returns:

0: "0"
1: "1"
2: "2"
3: "3"
4: "4"
5: "5"
6: "6

If anyone could provide assistance or guidance on how to resolve this issue, it would be greatly appreciated!

Answer №1

If you want to retrieve the first element of the response's data array, you can utilize the concept of Destructuring assignment. This will allow you to store the first element in a variable named result:

const response = {
  "statusCode": 200,
  "status": "success",
  "data": [
    [{
        "city": "Alexandria",
        "country": "Egypt",

      },
      {
        "city": "Alexandria",
        "country": "Egypt",

      },
    ]
  ]
}
const getData = ({ data: [result] = [[]] }) => result

console.log(getData(response))

Answer №2

retrieveData = function(response){
    valuesArray = response.responseValues[0];
    updatedData = []
    for(var value in valuesArray){
        updatedData.push(valuesArray[value])
    }
}

I trust this information proves beneficial to your endeavors.

Answer №3

When dealing with the data[0] array, using Object.keys(array) will actually return an array of the indexes found within that particular array. For example:

array= [{x: 1}, {x: 2}, {x: 3}]
Object.keys(array) // ['0', '1', '2']

The values pushed into the return array are simply the index numbers themselves, as demonstrated.

To prevent confusion, it is advisable to use distinct variable names. In this scenario, consider utilizing a different name like data.

Below is the updated function:

const object = {"statusCode": 200,"status": "success","data": [[{"city": "Alexandria","country": "Egypt",},{"city": "Alexandria","country": "Egypt",},]]}

getData = function (arr) {
  data = []
  arr[0].forEach(function (key) {
    data.push(key);
  });
  return data
}

console.log(getData(object.data))

Answer №4

If you want to extract the data from both an object and an array, you can utilize destructuring:

const fetchData = ({ data: [info] = [] } = {}) => info;

const results = {"statusCode":200,"status":"success","data":[[{"city":"Alexandria","country":"Egypt"},{"city":"Alexandria","country":"Egypt"}]]};

console.log(fetchData(results));

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

Failed: Protractor could not synchronize with the page due to an error saying "angular is not present on the window"

I encountered an issue with my Protractor test scripts where I started receiving an error message. Everything was working smoothly until I made some updates to a few scripts in my projects. The error occurs at the end of running the scripts. I attempted ...

Angular pop-up message not displaying title or content

I have integrated the toaster directive into my AngularJS web project. Following the documentation, I have declared the container on my view as shown below. <toaster-container toaster-options="{'time-out': 3000, 'close-button':true ...

Using Google Apps Script to upload a text file to Google Drive

It seems like uploading a file should be straightforward. However, I'm struggling with understanding blobs. function createFileUploader() { var app = UiApp.createApplication(); var panel = app.createVerticalPanel().setId('panel'); v ...

What is the reason behind being limited to sending only 5 requests if I fail to heed the data event?

I've come across some related questions while researching this topic, such as Why is node.js only processing six requests at a time?. However, I am still struggling to fully grasp the specifics. Below is a breakdown of my scenario: Firstly, let&apos ...

Improving efficiency by saving and loading the form value using best practices

One of the challenges I'm facing is how to populate dropdown selections on a webpage without resorting to hard-coded procedures. The code snippet below illustrates the current setup: <td> <ui-select ng-model="user_profile.gender" require ...

A guide on mapping an array and removing the associated element

I have an array called responseData, which is used to display the available card options on the screen. public responseData = [ { id: 1399, pessoa_id: 75898, created_at: '2022-11-08T16:59:59.000000Z', holder: 'LEONARDO ', validade: ...

Looking for an improved, tidier, or more efficient alternative to PHP Random Text?

Is there a more efficient way to generate random text other than using the random_text function in PHP? I'm interested in a method that is quick to render and light on server resources for faster page loading. Should I consider alternatives like Javas ...

PHP error: Unexpected non-whitespace character in JSON parsing

I am facing a challenge with displaying a large amount of DB data using PHP/SQL. It takes too long and the result is too big to show all at once. Therefore, I decided to use AJAX to display the data. However, when I tried encoding the data to JSON in my P ...

Shadow and Quality Issues with SVG Images

I have designed a unique SVG image with intricate details and a decorative frame, enhanced with shadowing effects. Unfortunately, after importing this SVG into a react-native application using the react-native-svg library, I noticed that the shadow around ...

Is there a way to incorporate various string values in a single function?

I am relatively new to programming and currently working on a project to display GPS locations from Lightroom on a Google Maps interface. After printing the strings to the screen, I can see 5 different values as expected. However, I am struggling to use t ...

Wordpress is experiencing a recurring issue with scripts being loaded multiple times

Currently, I am attempting to load some of my scripts from CDNs such as CDNjs and Google. While the scripts are loading correctly, I have noticed a strange issue where each script seems to generate two or even three HTTP requests (for the same script). You ...

react-responsive-carousel: setting a specific height for thumbnail images

After setting a fixed height for the image, I noticed that the same height is also being applied to the thumbnails. How can I avoid this issue? <Carousel width="600px" dynamicHeight={false}> {data?.book?.images.map((image, i) => ( ...

What is preventing the click function on a dynamically created button from being executed in jQuery?

Take a look at this jsFiddle where I illustrate my issue. Whenever I click on the "Add an ingredient" button, the button click event is triggered. My issue arises when I click on the "Create a subtitle" button because it dynamically creates "Add an ingredi ...

Warning: The use of 'node --inspect --debug-brk' is outdated and no longer recommended

Encountering this error for the first time, please forgive any oversight on my part. The complete error message I am receiving when running my code is: (node:10812) [DEP0062] DeprecationWarning: `node --inspect --debug-brk` is deprecated. Please use `node ...

Utilizing Locale to Rewrite URLs in Next.js Version 13

I've been attempting to rewrite the URL based on the locale extracted from my middleware.js, but for some reason, the URL isn't being rewritten and leads to a page-not-found error 404. Strangely though, if I manually navigate to "localhost:3000/e ...

Guide on transferring object between two $states using ui-router

Visit this link for more information Expected Behavior Upon logging in, selecting a Ticker button is expected to trigger the display of matching Tags for that specific Ticker. Actual Results However, upon clicking a Ticker button after logging in, the ...

Tips for detecting when no checkboxes in a group are selected or when at least one checkbox is selected, and then applying a class to the corresponding div

<div class="accordion-group"> <div class="accordion-heading"> <a href="#collapse" data-parent="#accordionQuiz" data-toggle="collapse1.." class="accordion-toggle"> <strong>1...</strong> Question ...

Excess space at the bottom of the Heatmap chart in Highcharts

I am facing an issue with a heatmap having extra space at the bottom that I cannot seem to remove. Despite trying various solutions from different Stack Overflow threads, such as adjusting chart.marginBottom, chart.spacingBottom, x and yAxis margins, and d ...

The issue of a non-functional grid with scroll in a flexbox

I've encountered a problem while working with the grid layout using divs and flexbox. The header, which I want to be fixed, is overlapping with the first row and I'm struggling to get the scrolling behavior right. How can I address this issue? I ...

Creating a dynamic table accordion with PHP and MySQL

I am currently working on creating an accordion table to display data retrieved from a database. I want the description data to be shown in a row below when clicking on the respective row. Despite my efforts in modifying various code snippets that I have c ...