Home > other >  How to get multidimensional array from JSON in Typescript?
How to get multidimensional array from JSON in Typescript?

Time:11-18

Here is a JSON array.

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

}

And I want to get array from this. How should I implement it in Typescript? I tried several things, but none of them worked. There is also a JSON array with only names as shown below, but I don't know how to use it.

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

I tried like bellow, but it doesn't work.


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

But following error occur.

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

Please let me know if you know how. Thanks.

CodePudding user response:

Arrays cannot have string indexes. Use an object type instead, for example:

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

You can then access the object with array notation.

CodePudding user response:

Probably due to these lines:

let aryCars: string[][] = [];

aryCars[name].push(car);

You've declared aryCars as an array, which implicitly has number indexes, but you're indexing using the string name.

Perhaps you actually want aryCars to look like this:

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

which is an object that has string keys, and an array of strings as values.

Then your code would be:

const aryCars: { [key:string]: string[] } = {};
names.forEach((name: string) => {
    aryCars[name] = cars[name]
});
  • Related