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");
}
我有一个用户对象,我已经通过硬编码添加了 2 个用户。
我的对象是嵌套对象,第一个键是用户的帐号,我将他们的数据嵌套在其他对象中。 我想要的是从输入字段中添加其他用户。我正在接受用户名、地址和帐户类型。
我想在我的其他用户之后将数据附加到我的用户对象。我已经尝试过 append 但它给我错误 .append is not function 。
最佳答案
您有一个 JavaScript 对象,而不是列表或数组,因此您无法向其推送。但是,您可以像这样定义一个具有关联值的新键:
users[accountNumber] = {
name,
address,
accountType: type,
deposits: 0,
withdraws: 0,
balance: 0
};
如果你想删除一个对象,你可以这样做
delete users[accountNumber]
重要的是要记住像您这样的 JavaScript 对象有效地充当字典(键/值对),其中数组只是一个列表。如果您想要列表的行为,那么您可以稍微更改您的对象定义,使其看起来像:
let users = [
{
accountNumber: '123',
otherFields: ''
}
];
users.push({accountNumber: '1234', otherFields: 'test'});
然而,您将失去通过帐号直接访问对象的能力,这完全取决于最适合您的要求。
关于javascript - 我如何将我的数据附加到嵌套对象中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52499105/