2017-02-05 110 views
1

我是一名JavaScript初學者,我無法動態創建下面的對象。所有名稱必須從文本條目中提取並動態插入到對象中。如何動態設置JS對象屬性名稱

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

這是我寫的代碼:

var name = form.name.value; 

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

回答

2

基本代碼:

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

要添加一個新用戶:

var name = form.name.value; 
var age = form.age.value; 
object.users[name] = { 
    name: name, 
    age: age 
} 
+0

警報(object.users [約翰]。年齡); 如何獲取? –

+0

'object.users [「john」]。age'你需要有引號。 – TricksfortheWeb

1

可以動態地設置對象鍵這樣的:

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 
      } 
     } 
    } 
*/