Extract and process all the data from the JSON array using TypeScript

Given a JSON array as shown above, the task is to extract all the values from the array and create a new array of arrays.

The challenge is to achieve this without using any model files in Typescript, and the method to do so is not clear.

Assistance in resolving this issue would be greatly appreciated.

[
  {
    "firstName": "Rajesh",
    "lastName": "Kumar",
    "age": "25"
  },
  {
    "firstName": "john",
    "lastName": "david",
    "age": "26"
  }
]

The desired output should be as follows:

[["Rajesh","Kumar","25"],["john","david","26"]]

Answer №1

If you want to transform all the values in the array, you can utilize the <Array>.map method. You have the option to return the object as an Array using <Object>.values or simply by specifying the desired keys like

[obj.firstName, obj.lastName, obj.age]

While you could iterate through the array and modify the values using a for loop, it can be quite verbose. The recommended approach in this scenario would be the first method, as it offers more flexibility.

The revised code would look like this

let data = [
  {
    "firstName": "Rajesh",
    "lastName": "Kumar",
    "age": "25"
  },
  {
    "firstName": "john",
    "lastName": "david",
    "age": "26"
  }
];
// Storing the array in the 'data' variable

data = data.map(item => Object.values(item));

// 'data' now holds the transformed array

You can explore alternative methods as indicated, but this is the most succinct approach.

Answer №2

You can find exactly what you need here

const data = [
  {
    "name": "Alice",
    "surname": "Smith",
    "age": "30"
  },
  {
    "name": "Bob",
    "surname": "Jones",
    "age": "35"
  }
];

// The desired array is stored in the variable result
const result = data.map(item => [Object.keys(item).map(key => item[key])])

// Alternatively, you can specify the properties explicitly
const result = data.map(item => [item.name, item.surname, item.age])

Answer №3

One way to simplify the objects with a few elements is to use the following approach:

const people = [
  {
    name: 'Sarah',
    surname: 'Jones',
    age: '30'
  },
  {
    name: 'Michael',
    surname: 'Smith',
    age: '35'
  }
]

const result = people.map(p => [p.name, p.surname, p.age])
console.log(result)

Answer №4

To achieve the desired outcome, consider implementing the following solution:

let updatedArray: any[] = [];

// objects - your array of objects

for (let item in objects) {

  let itemArray = [];
  itemArray.push(item.firstName);
  itemArray.push(item.lastName);
  itemArray.push(item.age);
  
  updatedArray.push(itemArray);
 }
 
 console.log("Updated Array: ", updatedArray);

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 trouble getting NPM environment variables to function properly on a Windows system?

I have a confusion in my package.json file where I am attempting to compile less code using versioning. Here is an example of what I am trying to achieve: "scripts" { ... "build:css": "lessc --source-map css/index.less build/$npm_package_name.$npm_package ...

Is it possible for Angular components to retrieve information on the current route and parameters?

I am struggling to understand why it's so difficult... why we are not supposed to care about the route from outside the routed component.... HOWEVER: I am attempting to develop a service so that my header (and any other component) can have access to ...

Angular CLI Issue: Project Configuration Not Detected

I've been attempting to execute an Angular program that was developed by a coworker, but I keep encountering the same error message: "The serve command needs to be run in an Angular project, yet a project definition cannot be found." Even after runnin ...

Instead of printing only the JSON data using "response.data", the entire response is being printed out

I'm making a GET request from an AngularJS 1.5x client to a Java HTTP method. In the client, I want to display the response that includes some JSON data. // This is a method from an Angular service that sends AJAX requests this.getTask = function(tas ...

Error encountered in the onPostExecute method due to a type mismatch at line 111 in JSON.java, along with a JSONException stating that the input has ended at character 0

Days have passed, and I am still searching for an answer. As a beginner in android development, I am struggling with the error messages org.json.JSONException: End of input at character 0 and org.json.JSON.typeMismatch(JSON.java:111) appearing in my onPost ...

Round Community - Numpy Essentials

Trying to implement a circular neighborhood operation on a 2D numpy array where the minimum pixel value is replaced by the average within a circular neighborhood with a radius of x. I attempted using a kernel based generic_filter, but encountered issues a ...

An exploration on integrating a controller into an Angular directive class using Typescript

Here's the TypeScript code for an Angular directive class I've been working on: I'm wondering how I can incorporate a controller into this directive without creating a separate controller class. My goal is to write and inject the ISOLATE SC ...

Using an array in Swift to set the title of a button

I am currently working on a project involving a google map with buttons as markers. In order to set the marker position and title, I am using the following code: self.mapView.delegate = self let camera = GMSCameraPosition.camera(withLatitude: -7.034323799 ...

Sending boolean values from parent components to child components in Angular 2

Is there a way to pass boolean values from a parent to child component without involving the template file? I am familiar with the normal method of communication between parent and child components using the template file, but I am not sure how to achieve ...

What are some effective strategies for handling JSON APIs efficiently?

What are some effective methods for working with RESTful JSON web services? It would be ideal for me to be able to work with POJOs that are automatically populated after calling a web service that returns JSON data. The web service does not offer any sch ...

Angular - Javascript - Oops! The variable 'google' seems to have gone missing after reloading the page

For my website, I utilized Angular 2+ and integrated the Google Maps Api by adding the following code to my index.html file: <script async defer src="//maps.googleapis.com/maps/api/js?[myKey]&libraries=places"> </script> ...

Ways to organize a struct array in increasing order in C++

In my c++ code, I have an array containing a struct. struct radius {double r; double angle; double x; double y;}; radius LOCAL[1000]; My goal is to sort the LOCAL array based on the value of r in ascending order. I have done some research online and mos ...

Arranging Objects by Alphabetical Order in Typescript

I am struggling with sorting a list of objects by a string property. The property values are in the format D1, D2 ... D10 ... DXX, always starting with a D followed by a number. However, when I attempt to sort the array using the following code snippet, it ...

Failure to display JSON data utilizing the getJSON method

$('document').ready(function() { $.getJSON('news.php', parseInfo); }); function parseInfo(data) { alert(data.news);//undefined $('#info').html(data.news); } My PHP output(news.php) shows [{"id":"2011042 ...

Back up the essential data of the core system, focusing on just one

One of my main goals for my application is to enable data backup and exchange between users. Specifically, I am looking to export a single entity without having to export the entire database. While I have come across some resources on backing up the entir ...

Associating information with a dropdown menu

My goal is to bind a drop-down using a global variable (the array name). The binding works correctly here: Click here - dropdown is populating fine var name = ['us', 'china', 'kenya', 'us', 'china', &ap ...

Error Message: "Module not found - Module TS2307 cannot be located

When I try to open a Typescript project in VSCode, I encounter the error message "ts2307 Cannot find module 'react' or its corresponding type declarations". However, everything works fine when I use WebStorm. The project was created using Create ...

Troubleshooting issue with Angular2 Dart ngFor not refreshing view with WebSockets data stream

Recently, I've been facing an issue with an Angular2 component. Whenever I use websockets, the view fails to update properly. Interestingly, everything runs smoothly when I make http requests, but I really need to ensure that the data in the view stay ...

Are Double-Value Additions in JSON Causing a C# Anomaly?

In the title, it was mentioned that values are being extracted from a JSON string, with "." being replaced by ",", converted to double and then added together. However, an anomaly has been observed where even though the string only consists of 2-digit numb ...

Inconsistency in product returns following promise mapping - Utilizing Ionic, Angular, and Typescript

When I retrieve items from a database for a feed, it is crucial that they remain in the same order as retrieved. However, despite mapping the array from the query, the displayed feed objects end up out of sequence. Here's the snippet of code: let ...