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.

Talon
  • 4,937
  • 10
  • 43
  • 57

2 Answers2

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

xkeshav
  • 53,360
  • 44
  • 177
  • 245
  • @diEcho.peopleList is an Object but not an Array.So OP should use peopleList.3.name //will return Jordan – 刘伟科 Oct 18 '11 at 04:50
  • 1
    `peopleList` contains a single member (object), which contains an array containing three objects,Members can be retrieved using dot or subscript operators. – xkeshav Oct 18 '11 at 05:01
  • 3
    @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. – Jonathan Lonowski Oct 18 '11 at 05:10
  • Ok,I have changed my answer.Thank you~ – 刘伟科 Oct 18 '11 at 05:39
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.

xkeshav
  • 53,360
  • 44
  • 177
  • 245
刘伟科
  • 432
  • 3
  • 12