1

I'm a beginner in javascript and I'm having trouble creating this object below dynamically. All names must be extracted from a text entry and dynamically inserted into the object.

var object = {
        "users" : {
            // Names dynamically inserted
            "Isaac" : {
                "name" : "Isaac de Araujo Meneses",
                "age" : "25" 
            }
            "John"{
                "name" : "John Miller",
                "age" : "32" 
            }
        }
    }

This is the code that I wrote:

var name = form.name.value;

    var object = {
        "users" : {
            // Names dynamically inserted
            name : {
                "name" : name,
                "age" : "25" 
            }
        }
    }

2 Answers 2

2

Base code:

var object = {
  users: {
    "John": {
      name: "John Smith",
      age: "140" // Why not?
    }
  }
}

To add a new user:

var name = form.name.value;
var age = form.age.value;
object.users[name] = {
  name: name,
  age: age
}
Sign up to request clarification or add additional context in comments.

2 Comments

alert(object.users[john].age); How to acess this?
object.users["john"].age you need to have the quotes.
1

You can set the object key dynamically like that:

var name = form.name.value; //suppose you get 'Isaac' here

var object = {
    "users" : {
    }
}

object.users[name] = {
    name: name,
    age: 25 
}

console.log(object);
/*
{
    "users": {
            "Isaac": {
                "name": "Isaac",
                "age": 25
            }
        }
    }
*/

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.