Guide to transforming JSON data into a different structure

My API is currently providing data in this format:

[
    {
        "lattitude": 52.57812538272844,
        "longitude": -1.7111388218750108,
    },
    {
        "lattitude": 53.043884,
        "longitude": -2.923782,
    }
]

I need to transform the data so that latitude becomes 'lat' and longitude becomes 'lng' like below:

[{
            lat: 52.57812538272844,
            lng: -1.7111388218750108,
        },
        {
            lat: 52.3602160,
            lng: 4.8891680,
}]

There are some missing fields which I will address later. Is there a way to achieve this without altering the API? I am using Angular-nativescript with a .net backend.

Answer №1

Is the information staying the same for you? Or is it something that can be observed?

If the data remains static, you can utilize the map function on arrays. This function converts an array into a new array.

const details = [
    {
        "latitude": 52.57812538272844,
        "longitude": -1.7111388218750108,
    },
    {
        "latitude": 53.043884,
        "longitude": -2.923782,
    }
];

const newData = details.map((point: any) => ({lat: point.latitude, lng: point.longitude }));

If the data is observable, just give me a heads up and I'll provide assistance in that area too.

Answer №2

data = data.map(entry => ({ latitude: entry.lat, longitude: entry.lng }));

or

function updateProperty(object, oldPropertyName, newPropertyName) {
  object[newPropertyName] = object[oldPropertyName];
  delete object[oldPropertyName];
}

data.forEach(entry => {
  updateProperty(entry, "lat", "latitude");
  updateProperty(entry, "lng", "longitude");
});

Answer №3

After experimenting with Nativescript + Angular, I discovered a new approach that successfully resolved the errors encountered in previous methods.

Below is the code snippet I implemented:

// Retrieve data from the API
getBusinesses() {
    let baseUrl = environment.apiUrl + 'business/locations';
    this.http.get(baseUrl).subscribe(response => {
        // Process the response data using createData function
        this.createData(response);
    }, error => {
        console.log(error);
    });
}

// Map and manipulate the data
createData(data) {
    var newData = data.map(item => ({
            lat: item.latitude,
            lng: item.longitude,
            title: item.address,
            subtitle: item.description,
    }));
    console.log(newData);
}

The updated output now looks like this:

JS: [{
JS:   "lat": 52.57812538272844,
JS:   "lng": -1.7111388218750108,
JS:   "title": "Non deserunt labore sunt ex laboris et adipisicing ullamco officia minim.",
JS:   "subtitle": "test"
JS: }, {
JS:   "lat": 53.043884,
JS:   "lng": -2.923782,
JS:   "title": "Non deserunt labore sunt ex laboris et adipisicing ullamco officia minim.",
JS:   "subtitle": "test"
JS: }]

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

How to incorporate JSON into a d3.js calendar display?

Learning d3 charts and javascript has been quite challenging for me. After researching a lot, I successfully populated the chart with CSV data. Now, my next goal is to populate the chart with json data. This is the code I'm using, which is inspired ...

MongoDB data not appearing when accessing the RESTful API

For practice I have created a simple RESTful API, but when I try to access the URL e.g. localhost:3000/people, it only shows an empty array like this [ ]. There are no errors in the console. I am using the node-restful package to build the API. This is th ...

Working with nested arrays of objects in Jsoncpp

Trying to navigate through a JSON file using the jsoncpp library has been quite the challenge for me. I am struggling with accessing the innermost array. Any helpful insights? { "key": int, "array1": [ { &quo ...

Angular fails to recognize a module that is clearly located in the node_modules directory

After creating an Angular library to manage authentication and successfully using it in various projects via NPM, I encountered a problem. Despite initially testing the library with npm link and publishing it privately to npm, I now face errors when trying ...

Encountering a permission issue while trying to execute npm install -g @angular/cli command

I recently started using Angular and am working on a new project. However, when I try to execute the following command: npm install -g @angular/cli I encounter the error message below: npm WARN checkPermissions Missing write access to /usr/local/lib/no ...

When using Loopj to perform a Put or Post request with basic authentication, the response may sometimes be null

In an effort to utilize Loopj for synchronous put and post calls from an HTTP utility class, the code utilizes a synchronous client within an AsyncTask. Certain UI interactions heavily rely on the JSON response, hence the AsyncTask is responsible for man ...

Encountering an issue with importing typeDefs in Apollo Server (Typescript) from an external file

I decided to move the typeDefs into a separate file written in typescript and then compiled into another file. Upon doing so, I encountered the following error: node:internal/errors:490 ErrorCaptureStackTrace(err); ^ Error [ERR_MODULE_NOT_FOUND]: Una ...

Encountering problems with parsing a lengthy JSON file

Can you spot the issue here? let stringinsta = JSON.parse({ "access_token":"129261**5ea59a4da481c65", "user":{ "username":"carlos_bellesso", ...

Error caused by Gson Overflow

While attempting to convert a Json string into a Java object using the Gson library, I encountered a StackOverflowException. java.lang.StackOverflowError com.google.gson.internal.$Gson$Types.checkNotPrimitive($Gson$Types.java:431) com.google.gson ...

A guide to configuring VSCode to recognize the DefinitelyTyped global variable (grecaptcha) within a Vuejs 3 TypeScript project

I have recently set up a new project using Vue.js 3 and TypeScript by running the command npm init vue@latest. I now want to integrate reCaptcha v2 into the project from scratch, without relying on pre-existing libraries like vue3-recaptcha-v2. Instead of ...

Tips for creating Junit tests for a CDK environment

As a newcomer to CDK, I have the requirement to set up SQS infrastructure during deployment. The following code snippet is working fine in the environment: export class TestStage extends cdk.Stage { constructor(scope: cdk.Construct, id: string, props: ...

In PHP, upload a .dat file so that it can be saved as a JSON file

I'm attempting to upload a .dat file and extract its content in JSON format. Here is the code I am using: HTML: <form action="upload.php" method="post" enctype="multipart/form-data"> <input type="file" name="fileUpload"> < ...

Using ASHX to Return JSON in ASP.NET

I have implemented autocomplete functionality on my website. The JavaScript part is complete and I am able to retrieve the MembershipUser object of the matching user. Now, I need to format the JSON response as follows: { query:'Li', suggestio ...

Is there a method to incorporate lists of varying types in a single v-for loop without causing any issues with type validations?

My current component is designed to display two different datasets, each with their own unique nature of data: state.articleTypeList: string[] state.renderPriceClassNameList: {[key: string]: string[]} To render both datasets within a single v-for componen ...

Typescript may fall short in ensuring type safety for a basic reducer

I have been working on a simple reducer that uses an object to accumulate values, aiming to maximize TS inference. However, I am facing difficulties in achieving proper type safety with TypeScript. The issue arises when the empty object does not contain an ...

Encountering difficulties with implementing reactive forms in an Ionic Angular 7 project as the app.module.ts file appears to be missing

Currently, I am working on a project using Ionic Angular 7 and I am facing some challenges with implementing reactive forms. Since app.module.ts is not in Ionic Angular 7 anymore, I tried to search for solutions online. Unfortunately, when I followed the i ...

When the buffer is sent through the socket in NodeJS, the console responds by stating that it is not recognized as a buffer

I've been exploring the implementation of AES encryption in ECB mode and here is the code snippet I'm working with. function encrypt (key, iv, plaintext) { if(algorithm == 'aes-128-ecb') iv = new Buffer(''); var ciphe ...

The versatile payment solutions offered by PayPal, including Adaptive Payments and Chained Payments, can be seamlessly

At this time, PayPal Adaptive Payments has been flagged as deprecated and there is no available frontend documentation. I have not been able to find a way to achieve this using the existing documentation. I am currently developing an Angular app that inte ...

What is the best way to transform this JSON data into an array of key-value pairs in JavaScript?

Dealing with nested JSON data can be challenging, especially when trying to extract key-value pairs efficiently. If anyone has suggestions on how to simplify this process and improve readability, please share your insights. The goal is to transform the ne ...

UI not reflecting updated form validation after changes made

Currently, I have a situation where I am passing a form from the Parent component to the Child component. All the validations are being handled in the Parent component and the Child component is simply rendering it. However, there is a specific field calle ...