1

So I have a JSON variable that looks like this:

var peopleList = {
    "1": {"Name": "Lisa", "item1": "Name of Item 1"}   ,
    "2": {"Name": "Marty"}   ,
    "3": {"Name": "Jordan",  "item1":"Name of Item 1",  "item2":"Name of Item 2"}
}

I guess it's kind of like a relational database.

Basically for the scope of the program i'm trying to do I need to be able to keep adding in multiple people (1-3 in this variable) and then associate multiple items to those people.

Also for the variable as it is now i'm not even sure what the getters and setters would be in Javascript.

For example, how would I add an item to "Marty"

And how would I print out the Name for item2 from person "Jordan"

Thanks for any help. I'm still a little bit new to JSON.

And if there is a better way to do this that is easier to parse, i'm all ears.

1
  • What's your reference? Marty or 2? Commented Oct 18, 2011 at 4:41

2 Answers 2

3

to get the value of any object with .

 peopleList[3].Name // will return Jordan

to add any key value pair to any object try this

var MartyData = peopleList[2];
MartyData['item1'] = "Name of item 1 of Marty";
// you can check now that data added or not
alert(peopleList[2].item1); // return Name of item1 of marty

DEMO

Sign up to request clarification or add additional context in comments.

3 Comments

@diEcho.peopleList is an Object but not an Array.So OP should use peopleList.3.name //will return Jordan
peopleList contains a single member (object), which contains an array containing three objects,Members can be retrieved using dot or subscript operators.
@LiuwkCn The dot operator only works with property names that are valid identifiers, which can't start with numbers. So Array or not, numeric properties have to be retrieved via bracket operators.
0

JSON Object is like Java Bean or Map.

var peopleList = {
'one':{'name':'Marty','item1':'Name of item1'},
'two':{'name':'Jack','item1':'Name of item1'},
'three':{'name':'Jordan','item1':'Name of item1','item2':'Name of item2'}
}

For example, how would I add an item to "Marty"

And how would I print out the Name for item2 from person "Jordan"

add an item to "Marty"

peopleList.two.item1 = "Name of item1"

print out the Name for item2 from person "Jordan"

alert(peopleList.three.item2);

===================================================
Sorry,I'm wrong.Edited.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.