0

When i try to get the type of an element using the below code it works.

var bodyContent = JSON.parse(response.content);

response.content  = typeof bodyContent.CompanyList.Company.Name;

Output response for above was String

Whereas if i try it in the below approach this does not work for the same JSON message. Please help

var bodyContent = JSON.parse(response.content);

var nameHolder = "CompanyList.Company.Name";

response.content  = typeof bodyContent[nameHolder];

Output was undefined

3 Answers3

1

That's because it's a nested object, you can't just pass a period delimited name and have it recursively drill down the tree (you'll have to implement that yourself).

It's the difference between

bodyContent["CompanyList"]["Company"]["Name"]; // former

and

bodyContent["CompanyList.Company.Name"]; // latter
Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308
0

There are 2 solutions for this issue.

You have to parse the nameHolder path. Reference: Accessing nested JavaScript objects with string key

or use eval but I'll not write about this since it's not a good practise.

Community
  • 1
  • 1
hsz
  • 148,279
  • 62
  • 259
  • 315
-2

It looks for a property called "CompanyList.Company.Name". This works:

var bodyContent = JSON.parse(response.content);
var list = "CompanyList";
var company = "Company";
var name = "Name";
response.content  = typeof bodyContent[list][company][name];
www.admiraalit.nl
  • 5,768
  • 1
  • 17
  • 32