Reputation: 6266
I have a json response from a service that looks like:
retrievedData:
{
"35736":{"Id":0, "Name":"car"}
,"48973":{"Id":0, "Name":"book"}
,"41981":{"Id":0, "Name":"dog"}
}
I want to get properties values using the numeric keys, for example:
console.log(retrievedData["35736"]);
There is a list of elements that it is iterated. Each element has a "serial" that matches the key property value.
When I use the hardcoded value:
console.log(retrievedData["35736"]);
It displays the correct object, but when I build the key like this:
var a = String('"' + JSON.stringify(element.Serial()) + '"');
console.log(retrievedData[a]);
it returns undefined
.
resultList.forEach(function (element) {
console.log("retrieved data, Serial:" + element.Serial());
var a = String('"' + JSON.stringify(element.Serial()) + '"');
console.log(a);
console.log(retrievedData[a]);
console.log(retrievedData["35736"]);
}
What am I doing wrong here?
The output values, console logs:
retrieved data, Serial:35736
v.ts:199 "35736"
v.ts:204 undefined
v.ts:206 Object {Id: 35736, Name: ""....
Any help will be appreciated.
Upvotes: 0
Views: 93
Reputation: 276303
it returns undefined.
Its because you have ('"' + JSON.stringify(element.Serial()) + '"');
The string will be something like ""35736""
not "35736"
Also using String
constructor is a very bad practice as its unconventional (e.g. typeof
will be different)
Upvotes: 2