Issue
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.
Solution
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.
Answered By - Chris Hamilton
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.