mid*_*mer 1 javascript nested object
let users = {
142201801: {
name: "Pankaj Jaiswal",
address: "Om sai rcm shopy , 400089",
accountType: "Saving",
deposits: 20000,
withdraws: 15000,
balance: 5000
},
142201802: {
name: "John Deo",
address: "Om sai rcm shopy , 400089",
accountType: "Saving",
deposits: 20000,
withdraws: 15000,
balance: 5000
}
};
let accountNumber_inital = 142201805;
function accountMaker() {
let accountNumber = accountNumber_inital + 1;
let name = document.getElementById("userName").value;
let address = document.getElementById("userAddress").value;
let type = document.getElementById("accoutType").value;
console.log("Account made");
}
Run Code Online (Sandbox Code Playgroud)
我有一个用户对象,我已经通过硬编码添加了 2 个用户。
我的对象是嵌套对象,第一个键是用户的帐号,我将他们的数据嵌套在其他对象中。我想要的是从输入字段添加其他用户。我接受用户名、地址和帐户类型。
我想将数据附加到其他用户之后的用户对象。我已经尝试了追加,但它给了我错误 .append is not function 。
您有一个 JavaScript 对象,而不是列表或数组,因此您无法推送它。但是,您可以定义一个新键及其关联值,如下所示:
users[accountNumber] = {
name,
address,
accountType: type,
deposits: 0,
withdraws: 0,
balance: 0
};
Run Code Online (Sandbox Code Playgroud)
如果你想删除一个对象,你可以这样做
delete users[accountNumber]
Run Code Online (Sandbox Code Playgroud)
重要的是要记住,像您这样的 JavaScript 对象实际上充当字典(键/值对),其中数组只是一个列表。如果您想要列表的行为,那么您可以稍微更改对象定义,如下所示:
let users = [
{
accountNumber: '123',
otherFields: ''
}
];
users.push({accountNumber: '1234', otherFields: 'test'});
Run Code Online (Sandbox Code Playgroud)
但是,您将无法通过帐号直接访问该对象,这完全取决于最适合您的要求的方式。