1

i want to create nested elements of an Object in a loop this works manuel :

$tmp={ "items": {
 "key1": {"name": "alpha"},
 "key2": {"name": "bravo"},
 "key3": {"name": "charlie"}
 }
 }
 alert($tmp['items']['key2']['name'])

But how can i create all vals in a loop??? something like:

 for (var x = 0; x < 100; x++) {
 $tmp2={"key"+x: {"name": "name"+x}}
 $tmp.push($tmp2)
 }
 alert($tmp['items']['key0']['name'])

???

asked Jan 24, 2014 at 20:34
3
  • did you try it? what happened? Commented Jan 24, 2014 at 20:37
  • also, you can only push to an array, not an object. You would need to make items an array, and then do $tmp['items'].push($tmp2); Commented Jan 24, 2014 at 20:39
  • it will create new Keys "0","1"($tmp['items'][0]['key0']['name']) Commented Jan 24, 2014 at 20:44

2 Answers 2

3

Declare the container for your key/value pairs outside the loop, then use the [] syntax to add keys to the container inside your loop.

 $tmp = { "items": {} };
 for (var x = 0; x < 10; x++) {
 // $tmp.items is equivalent to $temp["items"]
 $tmp.items["key"+x] = { "name" : "name" + x };
 }

This results in:

{
 "items": {
 "key0": {
 "name": "name0"
 },
 "key1": {
 "name": "name1"
 },
 "key2": {
 "name": "name2"
 },
 "key3": {
 "name": "name3"
 },
 "key4": {
 "name": "name4"
 },
 "key5": {
 "name": "name5"
 },
 "key6": {
 "name": "name6"
 },
 "key7": {
 "name": "name7"
 },
 "key8": {
 "name": "name8"
 },
 "key9": {
 "name": "name9"
 }
 }
}
answered Jan 24, 2014 at 20:49
Sign up to request clarification or add additional context in comments.

Comments

1

You can do this:

var $tmp={ 'items': {} };
for (var x=0; x<100; x++) {
 $tmp['items']['key'+x]={ 'name': 'name'+x };
}
alert($tmp['items']['key0']['name']);

But the value of $tmp.items.keyN.name is just nameN seems meaningless ..

answered Jan 24, 2014 at 20:51

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.