简体   繁体   中英

How to get multidimensional array from JSON in Typescript?

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.

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.

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]
});

But note that the names you showed is an object called names with a property also called names which would mean you would have to do:

names.names.forEach(...)

If this isn't what you're looking for, then please show what you expect the output to be.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM