Discover the steps to transform the elements within an array to a particular structure

I am working with an API that has the following structure:

[
   {
      "id": 4,
      "code": "IN",
      "name": "India",
      "recordVersion": "6CB5C760-E145-4FFA-AC63-FAF5F36B6C80",
      "updatedBy": "Sini "
   },
   {
      "id": 59,
      "code": "UK",
      "name": "United Kingdom",
      "recordVersion": "3512B084-8DB7-48F6-9E01-C0861E2A128D",
      "updatedBy": "sinju "
   }
]

My goal is to transform it into the following format:

localizedData = [ 
    { 
        text: "India", 
        value: 4 
    }, 
    { 
        text: "United Kingdom", 
        value: 59 
    }
];

Any suggestions on how to achieve this conversion?

Answer №1

If you wish to assign the name property to text, and the id property to value.

const data = [
  {
    "id": 4,
    "code": "IN",
    "name": "India",
    "recordVersion": "6CB5C760-E145-4FFA-AC63-FAF5F36B6C80",
    "updatedBy": "Sini "
  },
  {
    "id": 59,
    "code": "UK",
    "name": "United Kingdom",
    "recordVersion": "3512B084-8DB7-48F6-9E01-C0861E2A128D",
    "updatedBy": "sinju "
  }
];

const transformedData = data.map(item => ({text: item.name, value: item.id}));

console.log(transformedData )

Exploring the Array.prototype.map() method can enhance your understanding for future use.

Answer №2

Here is a solution to assist you-----

             let dataResults = data;
               let array = [], element;
                 for (let index = 0, length = dataResults.length; index < length; index++) {
                      element = dataResults[index];
                      array.push({user: element.username, desc: element.description, 
                         title: 
                        element.name});
                               }

Answer №3

Consider the following array as your result:

const array =  { "id": 4, "code": "IN", "name": "India", "recordVersion": "6CB5C760-E145-4FFA-AC63-FAF5F36B6C80", "updatedBy": "Sini " }, { "id": 59, "code": "UK", "name": "United Kingdom", "recordVersion": "3512B084-8DB7-48F6-9E01-C0861E2A128D", "updatedBy": "sinju " } }

To achieve the desired outcome, you simply need to:

const newArray = array.map(item => ({label: item.name, id: item.id}));

By implementing the above code, you should be able to achieve the desired result

Answer №4

Feel free to give this a shot.

const information = [
  {
    "id": 4,
    "code": "IN",
    "name": "India",
    "recordVersion": "6CB5C760-E145-4FFA-AC63-FAF5F36B6C80",
    "updatedBy": "Sini "
  },
  {
    "id": 59,
    "code": "UK",
    "name": "United Kingdom",
    "recordVersion": "3512B084-8DB7-48F6-9E01-C0861E2A128D",
    "updatedBy": "sinju "
  }
];

const modifiedInfo = [];

for(i=0;i< information.length;i++){
modifiedInfo.push({text : information[i].name, value : information[i].id})
}

console.log(modifiedInfo)

Answer №5

Here are two solutions:

Method 1 :

var data = [
   {
      "id": 4,
      "code": "IN",
      "name": "India",
      "recordVersion": "6CB5C760-E145-4FFA-AC63-FAF5F36B6C80",
      "updatedBy": "Sini "
   },
   {
      "id": 59,
      "code": "UK",
      "name": "United Kingdom",
      "recordVersion": "3512B084-8DB7-48F6-9E01-C0861E2A128D",
      "updatedBy": "sinju "
   }
];

data.map((item) => {
item["value"] = item["id"];
item["text"] = item["name"];
delete item.id;
delete item.code;
delete item.name;
delete item.recordVersion;
delete item.updatedBy;
});

console.log(data);

Method 2 :

const data = [
  {
    "id": 4,
    "code": "IN",
    "name": "India",
    "recordVersion": "6CB5C760-E145-4FFA-AC63-FAF5F36B6C80",
    "updatedBy": "Sini "
  },
  {
    "id": 59,
    "code": "UK",
    "name": "United Kingdom",
    "recordVersion": "3512B084-8DB7-48F6-9E01-C0861E2A128D",
    "updatedBy": "sinju "
  }
];

const result = [];

for (var item of data) {
  result.push({value : item.id, text : item.name});
}

console.log(result);

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

Having problems saving data with JQuery.ajax

Is there a way to store data from a Textbox when the Button is clicked? I am currently using JQuery AJAX to accomplish this task, as shown below. Please note that these tags are placed inside the theme function. function theme_user_post_block($vars) { $t ...

Determine if an object hierarchy possesses a specified attribute

When passing a set of options as an object like this: var options={ sortRules:[ {...}, // rule 1 {...}, // rule 2 // etc. ], filterRules:[ {...}, // rule 1 {...}, // rule 2 // etc. ], etc ...

Utilizing the SmartSuggest jQuery plugin for seamless integration of JSON data

Recently, I acquired the jquery plugin named smart suggest and I am interested in feeding a json array as opposed to just an array. The existing data file, 'sample-data.php', displays: <?php $fruits = '{...}'; $vegetables = '{ ...

Obtain custom parameter data from a string

Searching for custom parameter values within a string is necessary. For instance, given the following string: aaa[111] bbb[222] ccc[333] ddd[444] I am looking to extract the value 111 associated with the parameter aaa, and so on... The specific paramete ...

AJAX Username verification failing to validate

Working with PHP and MySQL, I created a basic form which includes a textfield for the username and a submit button. The page is named checkusername.php. Additionally, I implemented an AJAX function for handling this process. Subsequently, there is another ...

Updating the scope in AngularJS/jQuery

I'm currently working on integrating AngularJS into a legacy system that heavily relies on jQuery. I'm facing some challenges when trying to update the scope after retrieving data from an Ajax call. Essentially, the system includes a dropdown th ...

Replacing the tbody element in React with centered text using inline styles ---If you want

I am working with an empty array in React that I translate into state. When the array is empty, I want to insert a text that says "no match events yet..." into a react-bootstrap Table's tbody. In the current setup, I am struggling to center the text ...

Error message: "An unexpected character '<' was found at the beginning of the JSON data while loading a glTF file in a Three.js

Trying to incorporate a .glTF file into a Three.js project using the GLTFLoader in my Vue application has been presenting challenges. Each attempt at loading the .gltf file with the GLTFLoader results in the following error being displayed in the console: ...

Discovering the Desired Key within a JSON Structure

For my c# project, I am utilizing the Json.net Library. Within this library, I have a lengthy JSON object with multiple subfields. Here is an example of the structure: { "count": 10, "Foo1": [ { "id": "1", "name": "Name1" }, { ...

How can I furnish TSC with TypeScript definitions for URI imports in a comprehensive manner?

import Vue from 'https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c5b3b0a085f7ebf0ebf7f4">[email protected]</a>/dist/vue.esm.js' If I submit the above code to TSC for compilat ...

Display an image in response to a button click using JavaScript

I am currently working on a feature that will display information when a radio button is pressed. I also want to include an image, but I am facing an issue where the text displays correctly but the image does not appear. What steps should I take to resolve ...

Clearing a textarea in jQuery that is populated with text

Having an interesting dilemma. I'm trying to clear a <textarea> and then replace it with new content. The functions in the JSFiddle will work perfectly fine if the textarea is left empty, but as soon as any text is manually typed into it, the me ...

What is the reason for receiving a JSX warning even though JSX is not being utilized in the code?

In my Vue.js component file using the Quasar framework, I have the following code block inside the <template>: <q-btn color="green" label="save & continue editing" @click="saveCase()" /> This snippet is par ...

Table borders disappear when loading PHP echoed tables with jQuery and Ajax

Currently, I am delving into the world of jQuery, PHP, AJAX, and MySQL. My objective is to retrieve a table from the MySQL server and exhibit it on a webpage. This involves two PHP files – one serves as the back-end script connecting to the database and ...

Creating an array of strings using data from a separate array of objects in JavaScript/TypeScript

I want to generate a new array of strings based on an existing array of objects, with each object belonging to the Employee class and having a firstName field: assignees: Array<Employee>; options: string[]; I attempted to achieve this using the fol ...

``req.body is not being properly populated when data is sent using form-data, causing

When I send data in my Node.js application as raw JSON/x-www-form-urlencoded from Postman, it gets passed successfully. However, when sending the data as form-data from either Postman or my Angular frontend, the req.body is coming back as undefined. I have ...

Searching an array for values that match another array and storing the indexes of the found values in a new array in [mongodb]

I am attempting to find a solution for searching an array field in each document of a Collection for specific elements that are contained in another array. The goal is to output the indexes of the found elements as an array. For instance: Let's cons ...

Can I link the accordion title to a different webpage?

Is it possible to turn the title of an accordion into a button without it looking like a button? Here is an image of the accordion title and some accompanying data. I want to be able to click on the text in the title to navigate to another page. I am worki ...

Increasing the nth-child Selector in Jquery

Referring to this I am looking to cycle through the nth-child selector, which involves: var i = 1; var tmp = $(this).find('td:nth-child(i+1)'); // I wonder how this can be achieved i++; I have rows with dynamically generated columns i ...

The incremental BR tag counter seems to be malfunctioning, there appears to be a missing element

Can anyone help me with the following code? I'm trying to add an incremental counter next to each BR tag in a lyric song, but it doesn't seem to be working as expected. <?php $lyrics = "<p>Every time when I look in the ...