Converting JSON to an Array in Angular 6

Hello everyone, I am attempting to convert JSON data into an object array in order to add this data to a Kendo grid. However, I keep encountering the following error:

Uncaught (in promise): TypeError: Cannot read property 'slice' of undefined

This error indicates that my data format is incorrect!

Here is an example of how the data is structured in the JSON file:

[
  {
    "orderNumber": 1,
    "orderTable": "905503111-9",
    "orderDescription": "Nullam porttitor lacus at turpis. Donec posuere metus vitae ipsum. Aliquam non mauris.",
    "orderDate": "5/4/2018",
    "orderPrice": 79
  }
]

What I want it to look like is:

{
  "data": [
    {
      "orderNumber": 1,
      "orderTable": "905503111-9",
      "orderDescription": "Nullam porttitor lacus at turpis. Donec posuere metus vitae ipsum. Aliquam non mauris.",
      "orderDate": "5/4/2018",
      "orderPrice": 79
    }
  ]
}

Below is an example of how I am currently accessing the JSON file (orders.ts):

import { orders } from './orders';
import { employees } from '../employee/employees';

@Component({
  selector: 'app-order',
  templateUrl: './order.component.html',
  styleUrls: ['./order.component.css']
})
export class OrderComponent implements OnInit {
  public result;
  public data = orders;
}

I have tried various solutions like json.parse() and json.stringify(), but so far without success.

Just a reminder: I am utilizing a JSON file (orders.ts) that is present within my project.

Answer №1

let orders = [
  {
    "orderNumber": 1,
    "orderTable": "905503111-9",
    "orderDescription": "Nullam porttitor lacus at turpis. Donec posuere metus vitae ipsum. Aliquam non mauris.",
    "orderDate": "5/4/2018",
    "orderPrice": 79
  }
];
let newOrder = {
    "orderNumber": 1,
    "orderTable": "905503111-9",
    "orderDescription": "Nullam porttitor lacus at turpis. Donec posuere metus vitae ipsum. Aliquam non mauris.",
    "orderDate": "5/4/2018",
    "orderPrice": 79
};

orders.push(newOrder)
console.log(newOrder);

Answer №2

If you want to achieve this, it can be done easily by ensuring that the name matches the data.

 data=[
 {
"orderNumber": 1,
"orderTable": "905503111-9",
"orderDescription": "Nullam porttitor lacus at turpis. Donec posuere metus vitae  ipsum. Aliquam non mauris.",
"orderDate": "5/4/2018",
"orderPrice": 79
}
];
let d={data}

console.log(d)

Alternatively,

let d={}
 d.data=[
{
"orderNumber": 1,
"orderTable": "905503111-9",
"orderDescription": "Nullam porttitor lacus at turpis. Donec posuere metus vitae ipsum. Aliquam non mauris.",
"orderDate": "5/4/2018",
"orderPrice": 79
}
]
console.log(d)

You will see the expected result printed out.

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

Error message in React NodeJs stack: "The property ' ' does not exist on type 'never' in Typescript."

Recently, I have been immersing myself in learning NodeJs, Express, React, monogoDB and Typescript after working extensively with MVC C# SQL Databases. For my first project, I created a simple Hello World program that interacts with an Express server to d ...

"Utilizing Logical Indexing with a Reduced Array" in the MATLAB environment

The matlab tutorial on matrix indexing provides the following information: Logical Indexing with a Smaller Array The logical indexing array is typically expected to have the same number of elements as the array being indexed. However, it's permiss ...

Every element within the array matches the most recently added object in C#

I've designed a class called "Player" that stores data for individual players. Although the class functions correctly, it encounters an issue when multiple instances are stored in a List/Array - all objects in the list end up being identical to the la ...

Utilizing the GET method for JSON parsing to populate a Spinner with displayed values

I am facing an issue while trying to populate values in Spinner using JSON parsing. The error message "centerID not found" keeps appearing and nothing is being displayed in the Spinner View. // Here is the API file I am working with BASE_URL : http://192 ...

Looking to easily upload a JSON file, parse its contents, and display it on my index page with just a single button click using AJAX

I have a file named Name stored in my content folder, written in Json format. My goal is to display the content of Name.text after clicking a button. I developed some parsing code to interpret the json data, but I'm unsure where to integrate it. I bel ...

Storing MongoDB data in local storage as an array using a GET request: A step-by-step guide

I need help with a service that sends a GET request to retrieve data from my MongoDB collection. I want to save this incoming data into the local storage as an array. API.SERVICE.TS getStorageLocationsList(){ this.setHeader(); return this.http.ge ...

Server's response of 4xx does not contain the expected JSON data

My .NET MVC website utilizes JSON for AJAX form Posts. When a validation error occurs, such as when a user misses a required field, the server returns the validation errors in a JSON object and sets the HTTP status code of the response to a number in the 4 ...

Adding new information to a list when a button is clicked: Combining Angular TypeScript with Laravel

Upon entering a reference ID in my system, it retrieves the corresponding record from the database. However, I am facing an issue where adding a new reference number overrides the existing record instead of appending it to the list. https://i.sstatic.net/ ...

Component in Angular with an empty variable in TypeScript

I'm encountering an issue on my web page where I have a loop calling a component multiple times. I successfully pass data to the component, but the problem arises when I try to display the value of an object in the component. In the component's H ...

The payload transmitted from JavaScript to Django Views is devoid of any content

I'm currently working on sending data from JavaScript to Django using ajax. Below is the code snippet I am using for this: var json_name = {'name': 123} $.ajax({ method: 'POST', url: ...

Obtaining JSON data through AJAX requests from different domains may result in receiving a JSON string format

I have encountered an issue with my cross-domain AJAX call. It seems that instead of receiving a JSON object as expected, I am getting a string from the API provider. Here is the code snippet for my AJAX request. $.ajax({ async: false, ...

Tips for ensuring your controls function properly and seamlessly when switching to another page

I utilized the instructions from this post to implement a slider. However, I encountered an issue with the controller when navigating to subsequent pages. While the controller functions correctly on the initial page, it duplicates the same values on the fo ...

Steps for connecting JSON data to a ListView control

Seeking assistance on binding JSON data to a list view control. The JSON content is structured as a re-serialized data table: [ { "Ch_ID":"27", "User_id":"1", "Ch_Name":"test1", "Ch_Description":"test1description", "Ch ...

The code in the Node.js/Express application remains unchanged even after making alterations to the source code

I apologize for the unorthodox title of this question. I struggled to find a concise way to describe my current issue. As a beginner in Node.js, I am attempting to create a simple node/express app. Initially, everything was going smoothly as I set up var ...

Is it possible to deploy universal apps on Firebase Hosting?

After successfully deploying my Angular 2 application to Firebase hosting, I have been pleasantly surprised by how user-friendly the setup is and how seamless the deployment process has been using CI. Currently, I am exploring the possibility of adding un ...

The *ngFor directive is not displaying any items

I'm facing an issue with my code. I am using *ngFor to display some data, but something seems to be off. Here is the structure of my code: In a src/app/mock-heroes.ts file: import { Hero } from './hero'; export const HEROES: Hero[] = [ { i ...

Tips for setting up automatic saving of a reactive form in Angular 4

Is there a way to automatically save content in a reactive form once the form is validated, without the need to click a save button? ...

Using Typescript to define a method that returns a value within a .then() function

Currently in the process of coding a function to add a user to a database, with the requirement of returning a promise with the specified User class that I have created: async createUser(user: User): Promise<User> { const userObject: User = user; ha ...

Easiest method for displaying a column from an associative array as comma-separated values in PHP (retrieved from a MySQL database)

After fetching data from a MySQL database, I have an associative array that contains various columns. One of the columns is labeled as AMOUNT, resulting in an array structure like this: Array ( [0] => Array ( [ID] => 259 [YEARMONTH] => 201105 [AM ...

The sort function in Reactjs does not trigger a re-render of the cards

After fetching data from a random profile API, I am trying to implement a feature where I can sort my profile cards by either age or last name with just a click of a button. Although I managed to get a sorted array displayed in the console log using the h ...