• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 325
  • Last Modified:

Make Members of JSON object accessable through a dynamic variable name

Hello,

I am new at JS programing, but have experience in C#, ASP.NET.

What i have is a JSON object, lets call it parts.  It is parsed and ready to go.

Now in that object I have 2 members - part1 and part2

now I want to do the equivelent of below (I know the sytax is incorrect, just consider it pseudocode.

for(var i = 1; i <= 2; i++){
      parts.("part" +i) = "HELLO" + i;
}

Open in new window


With the desired output of parts.part1 being "Hello1 and the desired output of parts.part2 being "Hello2"

The main problem is how to be able to use the for loop to update the member of the JSON object where the datamember name needs to be dynamicly updated?

Any help is appreciated.
0
paulpp
Asked:
paulpp
1 Solution
 
Julian HansenCommented:
Is this what you want?
for(var i=1; i<=2;i++) {
  parts['part'+i] = "Hullo " + parts['part'+i] + i;
}

Open in new window

0
 
BardobraveCommented:
To do what you are asking for you need to use an array inside your JSON object.

Your JSON object now should be something like this:

{ "parts1" : "Hello1", "parts2" : "Hello2" }

what you actually need is:

{ "parts" : [ "Hello1", "Hello2" ] }

This way you can access your different parts through:

for (var x = 0; x < yourJsonObject.parts.length; x++)
    alert(jourJsonObject.parts[x]);

Simply, instead of using a different parameter with a number inside your data class use an array to differenciate elements of the same type.
0
 
paulppAuthor Commented:
Perfect - thank you.
0

Featured Post

Prep for the ITIL® Foundation Certification Exam

December’s Course of the Month is now available! Enroll to learn ITIL® Foundation best practices for delivering IT services effectively and efficiently.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now