Trouble retrieving desired data from an array of objects in React Native

I'm having trouble retrieving values from an array of objects in my state.

When I try to access the values, it only prints out "[Object Object]". However, when I stored the values in a separate array and used console.log, I was able to see them. Here's an example:

var data=[{"coordinate":{"longitude":73.8679075241089,"latitude":18.515422222637756},"key":0,"color":"#ffc130"}];

console.log("data"+data[0].coordinate.longitude);

This is how I attempted to retrieve the value in a React Native project:

    console.log("location "+JSON.stringify(this.state.markers));
    var data=JSON.stringify(this.state.markers);
    console.log("datamap"+JSON.parse(data));
    var dataparse = JSON.parse(data);
    console.log("data parse "+this.state.markers[0].coordinate.latitude);

Here is where I declared the initial state and arrays:

class DefaultMarkers extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      region: {
        latitude: LATITUDE,
        longitude: LONGITUDE,
        latitudeDelta: LATITUDE_DELTA,
        longitudeDelta: LONGITUDE_DELTA,
      },
      markers: [],
    };
  }

My goal is to store the latitude and longitude in an array for further use.

Answer №1

In order to parse it, I utilized the functions JSON.parse() and JSON.stringify().

I obtained a parsed version by calling <strong>JSON.parse(JSON.stringify(this.state.markers))</strong>.

Answer №2

Update your console.log function by separating two values with a comma instead of concatenating them together.

Original Code:

console.log("location "+JSON.stringify(this.state.markers));

Updated code:

console.log("location ", JSON.stringify(this.state.markers));

You should now be able to successfully print the desired value.

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

Using Javascript to select a radio button in a form depending on the value entered in a text box

I have a form that interacts with a Google Sheet to insert and retrieve data. For instance, the form contains two radio buttons: <input id="Rdio_1" name="RdioSelect" type="radio" class="FirstCheck" value="1" onchange="RadioValInsert ()"/> < ...

The transformation in the resulting array is evident when a nested array is altered after being concatenated using Array.concat

MDN explains concat as follows: The concat() function is utilized to combine two or more arrays without altering the original arrays. Instead, it produces a new array. Let's examine the code snippet below: Example 1 const array1 = [['a& ...

Managing JSON data retrieval and manipulation with REST API in Node.js and MongoDB

My technology stack includes Node.js and MongoDB with a rest api. The input data I'm dealing with looks like this: var doc={"name":"ABX", duedate : new Date() } Before sending it to the server, I stringify the data: /rest/update?doc=JSON.s ...

When attempting to execute the 'npm start' command, an error was encountered stating "start" script is

Encountering an issue when running "npm start." Other users have addressed similar problems by adjusting the package.json file, so I made modifications on mine: "scripts": { "start": "node app.js" }, However, t ...

The hamburger menu unexpectedly appears outside the visible screen area and then reappears at random intervals

My website has a hamburger menu for mobile devices, but there's a problem. When the page loads on a small screen, the hamburger menu is off to the right, causing side scrolling issues and white space. I thought it might be a CSS problem, but after exp ...

The JQuery JavaScript function fails to complete its execution

Question: How can I resolve the issue where my PHP file returns a large JSON string with approximately 2000 elements, each having 14 child elements? When using jQuery AJAX to fetch the JSON and populate an ID-identified table, the filling process stops mid ...

What is the process for a server to transmit a JWT token to the browser?

Here is an example response sent to the browser: HTTP / 1.1 200 OK Content - Type: application / json Cache - Control : no - store Pragma : no - cache { "access_token":"MTQ0NjJkZmQ5OTM2NDE1Z ...

What are the consequences of incorporating getInitialProps within _document.js that leads to a crash in the Next.js application?

What are the implications of using getInitialProps in _document.js for static rendering? How can it potentially impact the overall static rendering process? Consider the following scenarios: A small e-commerce website with a mix of static and dynamic pa ...

What language should be used for JSON data formats?

I am dealing with a JSON file named myjson.cfg that has the following structure: { "values": { "a": 1, "b": 2, "c": 3, "d": 4 }, "sales": [ { "a": 0, "b": 0, "c": 0, "d": 0, ...

What is the best way to create a new variable depending on the status of a button being disabled or enabled

Imagine a scenario where a button toggles between being disabled when the condition is false (opacity: 0.3) and enabled when the condition is true (opacity: 1). Let's set aside the actual condition for now -- what if I want to determine when the butt ...

Is there a way to incorporate a text box in javascript that displays the retrieved reference count from the database?

I'm currently working on creating a functionality that retrieves rows with the same ID from a database and displays them in a text box. Below is the PHP code I've written for retrieving all the rows: PHP: <?php include_once('pConfig ...

How to effectively create factories in AngularJS

I stumbled upon this angularjs styleguide that I want to follow: https://github.com/johnpapa/angular-styleguide#factories Now, I'm trying to write my code in a similar way. Here is my current factory implementation: .factory('Noty',functi ...

Ways to verify the presence of users in the Database

I have successfully retrieved the data with the code below, but I am encountering issues with my script's if and else statements. Any tips or advice on how to improve this functionality? server.post('/like', (req, res,next) => { var ...

The Navigation Stops Working Following an Automated Redirect from a 404 Page to the Homepage with next/router and useEffect()

I encountered a problem with next/router. I created a '404 Page' and configured it to redirect clients back to the home page router.push('/') after 3 seconds. However, when clients return to the main page, they encounter a console error ...

When there is an expensive calculation following a Vue virtual DOM update, the update may not be

Currently, I am facing an issue with adding a loading screen to my app during some heavy data hashing and deciphering processes that take around 2-3 seconds to complete. Interestingly, when I removed the resource-intensive parts, the screen loads immediate ...

How to interact with AngularJS drop-down menus using Selenium in Python?

I have been working on scraping a website to create an account. Here is the specific URL: Upon visiting the site, you need to click on "Dont have an account yet?" and then click "Agree" on the following page. Subsequently, there are security questions th ...

In Node JS, the variable ID is unable to be accessed outside of the Mongoose

When working with a Mongoose query, I encountered an error where I am trying to assign two different values to the same variable based on the query result. However, I keep getting this error: events.js:187 throw er; // Unhandled 'error' ev ...

Unable to assign an ID to an element in JavaScript, as it will constantly be undefined

Is there a way to automatically generate unique IDs for jQuery objects if they don't already have one? I need these IDs for future requests. I wrote the following code, but it doesn't seem to be working. The ID's are not getting set and the ...

Is it possible for Angular's `HttpClient` to use complex property types in the `.get()` generics aside from just `string` or `number`?

After spending an entire day researching the topic, I've hit a dead end. All my efforts have only led me to discover one thing—omission. None of the information I've come across mentions whether you can utilize non-simple types (such as string ...

Conceal a list of items within a div that has a particular class

This is a sample of my HTML code: <div class="row"> <div class="col-md-12"> <div class="scrollbox list"> <ul class="list-unstyled"> <li id="articulate.flute">articulate flut ...