What is the best way to retrieve a value from one array based on its index in React Native?

Looking to populate the centreValues array with values from another array

    const centreValues=[
  {
    title:'Type',
    value:centreDetail.location_type
  },
  {
    title:'Address',
    value:centreDetail.address1+centreDetail.address2
  },
  {
    title:'City',
    value:centreDetail.city
  },
  {
    title:'State/Province',
    value:centreDetail.state
  },
  {
    title:'Postal/Zipcode',
    value:centreDetail.zip
  },
  {
    title:'Phone',
    value:centreDetail.phone
  },
]

The structure of my centreDetails JSON object is:

centreDetails={
   location_type:'some Value',
   address1: 'some Value',
   address2:'some Value',
   ....
}

How can I substitute these values into the centreValues array?

Answer №1

If you're dealing with a simple JS object and array situation, it looks like you need the centreDetail in your provided array. Check out the example below:

const centreDetail = {
     location_type: "something",
    city: "something",
    state: "something",
    zip: "something",
    phone: "something",
}

From here, you can access the properties in the object like this:

const centreValues=[
  {
    title:'Type',
    value:centreDetail.location_type
  },

  {
    title:'City',
    value:centreDetail.city
  },
  {
    title:'State/Province',
    value:centreDetail.state
  },
  {
    title:'Postal/Zipcode',
    value:centreDetail.zip
  },
  {
    title:'Phone',
    value:centreDetail.phone
  },
]

Update: You mentioned adding JSON to your question now. This means you'll need to incorporate a loop. Consider using a for loop or a while loop to iterate through each index of the array and add it to another array. You could also use map for this task.

Based on your feedback, everything seems to be working fine when I tested it in the console. Are you sure about the issue you mentioned?

https://i.sstatic.net/P9uYB.png

Answer №2

Below is a method to accomplish this task:

const centreDetails = {
   location_type:'my location',
   address1: 'an address',
   address2: 'another address',
   phone: '516546548',
   city: 'Wakanda'
}

const centreValues = Object.entries(centreDetails).map(([title, value]) => ({ title, value}))

console.log(centreValues)

You need to convert your object into an array containing key-value pairs using Object.entries()

After that, you can structure it as desired by using the map function on your array


UPDATE
To include only specific fields, you can apply a filter function:

const centreDetails = {
    location_type: 'my location',
    address1: 'an address',
    address2: 'another address',
    phone: '516546548',
    city: 'Wakanda'
}

const desiredValues = ["location_type", "address2", "city"]

const centreValues = Object.entries(centreDetails)
    .filter(([title, value]) => !!desiredValues.includes(title)) //Checks if the value exists
    .map(([title, value]) => ({ title, value}))

console.log(centreValues)


UPDATE 2 :

If you want to assign different aliases to the fields, here is one way to do it:

const centreDetails = {
    location_type: 'my location',
    address1: 'an address',
    address2: 'another address',
    phone: '516546548',
    city: 'Wakanda'
}

const desiredValues = {
    "location_type" : "location",
    "address2": "this guy's second address",
    "city": "Hey, he lives here !"
}

const centreValues = Object.entries(centreDetails)
    .filter(([title, value]) => desiredValues[title])
    .map(([title, value]) => ({ title : desiredValues[title], value}))

console.log(centreValues)

Answer №3

To retrieve all the values of centreDetail as an object result

centreValues.map(center => center.value.centreDetail)  

If you want to transfer it to another array and manage the state, do the following:

centreValues.map(center => this.setState({ centreDetailArray: [...this.state.centreDetailArray, center.value.centreDetail] })

You can then access the result from the state like this:

<View>  
  {this.state.centreDetailArray.map(centerDetail =><Text>{centerDetail}</Text>)}
</View>

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

What is the smallest server.js file needed to run a react/redux application?

I have successfully configured my project using webpack and babel for ES6 transpilation with the specified presets: { "presets": ["react", "es2015", "stage-1"] } My webpack production configuration is structured as follows: var path = require('pa ...

Capturing user input in HTML and passing it to JavaScript

I have a good grasp on how to implement input in HTML to execute JavaScript functions that are defined in the same directory as the HTML file. For example: <input type="button" value="Submit" onclick="someFunc(500)" > When the button is clicked, th ...

Tips for extracting specific elements from an array

I am working with an array structured like this: $articles = array([0] => array('title' => 'When ....', 'description' => '....', 'created& ...

Confirmation of numerous checkbox selections

I am facing a challenge with a form that contains multiple questions answered through checkboxes. I need to validate that at least one checkbox is selected in all the questions, otherwise an alert message should pop up. Is it possible to achieve this val ...

Create an event listener for clicking on an image that potentially has a corner ribbon obscuring a portion of it

In my project, there is a div element with an id of items containing several bootstrap cards. Each card includes an image tag and some are accompanied by the following HTML code: <div class="ribbon"><span>Sale</span></div> This co ...

Exploding particles on the HTML5 canvas

I've been working on a particle explosion effect, and while it's functional, I'm encountering some issues with rendering frames. When I trigger multiple explosions rapidly by clicking repeatedly, the animation starts to lag or stutter. Could ...

Mapping an array of objects within another array of objects

I have a collection of objects that I looped through to extract the content: const teamSliderContent = [ { Description1: 'Chef. Mordy Wenk', Title: 'Head of the Chief staff.', id: 1, }, { Desc ...

My HTML file is not able to load my Javascript file

I'm currently working on integrating a JavaScript code for a show more and show less feature on my page. The goal is to limit the description so that it shows only a certain number of characters, with an option to expand or collapse the text. However, ...

Iterate through an object, with certain keys being duplicated

Currently, I am facing a scenario where the object I'm analyzing is quite messy... Essentially, within this object... my goal is to locate the pageviews node, but only if it has an array of data... Here's an example of the data: data = [ ...

Generating and inserting information into a connected Llist

My journey into understanding Linked Lists has been a combination of watching videos and going through different examples. I have grasped the concept of what a Linked List is and how it can be compared to real-life analogies. However, when it comes to codi ...

No reply from Axios after using async await

Here's a simple method that utilizes Axios to make a call to an API. Interestingly, when the method is called, it doesn't display any output, no logs or error messages. async deActivate(product: Product): Promise<void> { try { ...

Iterating through a 2D array using KnockoutJS foreach loop

I am working on binding a JSON string returned from the server to a foreach loop using KnockoutJS. The JSON structure is as follows: [{"FileID":19, "ParentID":6, "SubType":"Page", "FileName":"nav_secondary_bg.png", "FileExtension":null,"Filetype":"20 ...

What are alternative ways to retrieve data from a different server using AJAX without relying on JSONP?

I am currently dealing with a project where the back-end code is located on ServerA, while my front-end code is on ServerB, belonging to different domains. Due to the same origin policy, I am facing difficulties in successfully making AJAX requests (both P ...

The functionality of the controller is not functioning properly in AngularJS

The button syntax is <div class="btn-group" align="center"> <button ng-click="myFunction()" id="one" class='btn btn-primary btn1' >Save Entry</button> <button ng-click="close_window()" id="two" class='btn btn-pr ...

The caption below the image is not functioning correctly when hovering over it

I'm having trouble getting the text to appear correctly underneath the image. Whenever I hover over the image, the text seems to overlap it. I am sure there is a simple solution to this issue, but I can't seem to figure it out. Removing the inlin ...

What is the step-by-step process for incorporating the `module` module into a Vue project?

ERROR Compilation failed with 6 errors 16:20:36 This specific dependency could not be located: * module in ./node_modules/@eslint/ ...

Setting a default value for Autocomplete in MaterialUI and React.js

Is there a way to set a default value for an Autocomplete TextField component from Material UI in React.js? I want to load a pre-populated value from the user's profile that can then be changed by selecting another option from a list. Check out my co ...

Include a new row in the form that contains textareas using PHP

I'm trying to add a new row to my form, but I'm facing challenges. When I click the add button, nothing happens. If I change the tag to , then I am able to add a row, but it looks messy and doesn't seem correct to me. Here is my JavaScript ...

Matching objects in an array based on a specific property using the key of another object

To display information in the UI based on matching values between the data.examples array object's name.value property and the keys in the wcObject.notCoveredList, we need to create a logic. If there is a match, all corresponding values from wcObject ...

A comparison of copyFileSync and writeFileSync

I've been working on file manipulations and I came across this interesting dilemma. I tried searching online for a solution but I couldn't find a good, precise answer. Which method do you think is more efficient for copying a file? readFileSync ...