Getting a multidimensional array from JSON in Typescript: A step-by-step guide

Below is a sample of a JSON array containing information about cars.

var cars = {
    "cars": {
        "john": [],
        "alex": [
            "ford"
        ],
        "hilton": [],
        "martin": [
            "ford",
            "ferrari"
        ],
        "david": [
            "Lamborghini"
        ],
        ...
    }

}

I am looking to extract arrays from this data structure using Typescript but have been unsuccessful. I also have another JSON array with just names which I'm unable to utilize.

var names = { 
    "names": [
        "john",
        "alex",
        "hilton",
        "martin",
        "david",
        ...
    ]
}

Here is the approach I've tried, but it's not working as expected.


let aryCars: string[][] = [];
names.map((name: string) => {
    cars[name].map((car: string) => {
        aryCars[name].push(car);
    });
});

When attempting this, I encounter the following error:

Element implicitly has an 'any' type because index expression is not of type 'number'.

If you have any insights on how to solve this issue, please share. Thank you.

Answer №1

It seems like the issue lies within these lines:

let carList: string[][] = [];

carList[name].push(car);

The problem here is that you've defined carList as an array with implicit numerical indexes, but you're trying to access it using a string variable name.

If your intention is to have carList structured differently, you might consider defining it like this:

const carList: { [key:string]: string[] } = {};

This way, carList will be an object with string keys and arrays of strings as values.

You can then modify your code to look something like this:

const carList: { [key:string]: string[] } = {};
names.forEach((make: string) => {
    carList[make] = cars[make]
});

Also note that if your 'names' variable is actually an object with a property named 'names', you would need to reference it as shown below:

names.names.forEach(...)

If this solution does not align with your desired outcome, please provide more information on what you expect the result to be.

Answer №2

String indexes are not supported in arrays. It is recommended to use an object type instead, like this:

let carObject: {
    [key: string]: string
} = {};

By using this approach, you can access the object using array notation.

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

Upon transitioning from Angular 5 to Angular 6, a noticeable issue arises: The existing document lacks a required doctype

I recently updated my project from Angular 5 to Angular 6. Post-upgrade, everything compiles without errors. However, when I try to access the website, all I see is a blank screen. Upon inspecting the console, I came across the following error message: Th ...

JSON data source - Sub-Category Array

Currently, I am utilizing iReport to create templates for JasperReports. My requirement involves using a json datasource. To illustrate this, let's consider the following example of my json data source: { "field1" : "value1", "list" : [ ...

Transferring information using TypeScript

My issue arises when transferring data from HTML in the following format Karbohidrat :{{karbohidrat}} <button ion-button (click)="cekHalamanMakanan('karbohidrat')">View carbohydrate foods</button> <br> Then, I retrieve the kar ...

Does anyone have a solution for resetting the ID numbers in a flatlist after removing an item from it?

As the title suggests, I am facing an issue with the following scenario: { id: '1', name: 'one' }, { id: '2', name: 'two' }, { id: '3', name: 'three' }, { id: '4', name: &apo ...

Combine a pair of select statements to utilize the RxJS store within an Angular Guard

When working on an Angular Guard, I encountered a challenge where I needed to select two fields from the ngrx store. Here is the code snippet for reference: @Injectable() export class RoleGuard implements CanActivate { constructor( public router: A ...

Encountering the error message "Attempting to access properties of undefined (specifically 'map')". Despite having the array properly declared and imported

I am facing an issue while trying to iterate through an array and display names for each person. Despite declaring the array properly, it is returning as undefined which is causing the .map function to fail. Can you help me figure out where I am making a m ...

Setting a maximum value for an input type date can be achieved by using the attribute max="variable value"

Having trouble setting the current date as the "max" attribute value of an input field, even though I can retrieve the value in the console. Can anyone provide guidance on how to populate the input field with the current date (i.e max="2018-08-21")? var ...

error": "message": "Property 'name' cannot be read because it is undefined

I've encountered an issue while creating a route to handle POST data. Despite testing it on postman, I have not been able to find a solution for the problem that many others seem to be facing as well. It seems like the 'name' field is not be ...

Upon completion of a promise in an express middleware and breaking out of a loop, a 404 error is returned

In my efforts to retrieve an array of object (car) from express using database functions in conjunction with the stolenCarDb object, everything seems to be working fine. However, when attempting the following code snippet, it results in a 404 error w ...

The URL for my JSON file cannot be located on my Angular server

Hey there! I'm currently working on setting up a server that will be pulling product data from a JSON file using HTTP. However, I've encountered an issue during the application build process where this error message pops up: Failed to load resou ...

Retrieving and showcasing data points from a JSON array within a Select Statement in Postgres

I'm currently working on developing code to retrieve values directly from a text field that contains JSON within a JSON array. My goal is to display these values along with an ID using Row_Number, but I'm facing some challenges. Additionally, I ...

How can you type a collection of initialized class instances in Typescript when given an object containing classes?

Imagine having an object that resembles the following: const typeMap = {category1: Category1, category2: Category2} In this case, Category1 and Category2 refer to classes, and there could potentially be hundreds of different categories. Now I also have a ...

POJO fields with empty values in application/json and BeanParam objects

I am facing an issue with a REST service operation in my controller class: @POST @Consumes({MediaType.APPLICATION_JSON}) @Path("create") public Response createWidget(@BeanParam Widget widget) { ... } The Widget class is a simple POJO bean with two pr ...

Tips for Implementing a Button Click Sound in Ionic 2

I've noticed that many native apps have a distinct click sound when buttons are pressed. Is there a way for me to add this same feature to all buttons in Ionic 2? ...

Merge arrays values with Object.assign function

I have a function that returns an object where the keys are strings and the values are arrays of strings: {"myType1": ["123"]} What I want to do is merge all the results it's returning. For example, if I have: {"myType1": ["123"]} {"myType2": ["45 ...

Issue with JSONB operations fetching arrays

Within a table named temporary_data containing a data field named temporary_data as well, housing the following JSON structure: { "FormPayment": { "student": [ { "fullname": "name stud ...

Output JSON data from PHP for use in Javascript

Is there a way to effectively convert JSON data from PHP/Laravel into JSON for JavaScript? I have the JSON string from PHP, but it is only rendering as a string. How can I convert it to a JSON object in JavaScript? Take a look at my code below. $('#e ...

Ways to leverage Composite API in place of Mixin or Extends functionality

Currently, I am exploring the use of Vue3 for my project. One issue I am facing is that I need to create multiple components (SFC) with similar properties. I want to define these common properties using the composite API across all components, like so: con ...

Verify if the array entries match

Within my select element, I populate options based on an array of values. For example: [{ name: 'A', type: 'a', }, { name: 'B', type: 'b', }, { name: 'B', type: 'b', }, { name: &apos ...

Employing the forEach method on an array to search for a specific string and subsequently retrieve a function

I'm currently working on implementing a discount code system using AngularJS. I've defined a function called $scope.pricetotal that represents a specific value, an input field to capture a string, and an array. Here's the main objective: I w ...