0

i want to create a array:

myarray:array [
 "test1" = [
    [0] = 
     {
      name: "mike",
      friend: "tom"
     }
    ]
 ]
 "test2": [
    [0] = 
     {
      name: "mike",
      friend: "tom"
     }
    ],
    [1] = 
     {
      name: "mike",
      friend: "tom"
     }
    ]
 ]
]

how i can dynamically add Objects?

In php i would do something like that:

$content = {name: "robert", friend: "mike"}
$myarray[$group][] = $content; // Group is the dynamic element

in Javascript i try this:

myarray[group].push({
 name: "mike", friend: "-"
})
// group is the dynamic element

but he failed with Cannot call method 'push' of undefined on the first call.

I don't know how many "groups" there are so i cannot init the array with all the group.

3
  • What is the value of group? Where you want to push? Commented Apr 8, 2014 at 8:51
  • Your array declaration is not valid. Commented Apr 8, 2014 at 8:54
  • @Mosho: Oh right thank you - i corrected Commented Apr 8, 2014 at 9:00

1 Answer 1

2

Use object instead array to hold the information:

Example:

function addUser(users, user, group) {
  if (!users[group]) {
     users[group] = [];
  }
  users[group].push(user);
  return users;
}

var users = {};

users = addUser(users, {name: "mike", friend: "-"}, 'test1');
Sign up to request clarification or add additional context in comments.

1 Comment

thank you. Is the necessary in javascript to check (L.2-4)? php would automatically set the array if it's not set before

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.