![](/img/trans.png)
[英]Create Objects inside an Object at Runtime(Dynamically) in Javascript
[英]Javascript Create Object inside Objects dynamically
我有一個空對象,想在對象內部動態創建一個對象。
const obj = {}
obj["test1"]["test1.1"] = x //initialize to some variable
我收到錯誤
Uncaught TypeError: Cannot set property 'test1.1' of undefined
我希望輸出像
obj = {
test1: {
test1.1: x //some variable
}
}
動態如果你的意思是屬性的名稱不確定,你可以使用括號插入動態變量名稱:
const arg1 = 'test1'; const arg2 = 'test1.1'; const x = 42; // assign both variable names dynamically const obj = { [arg1]: { [arg2]: x } }; console.log(obj);
您可以分兩步或一步完成此操作
const x = "some var"; const obj = {}; obj["test1"] = { "test1.1": x }; // assign the nested object console.log(obj); // or const y = "some var"; const obj1 = { // assign the complete object test1: { "test1.1": x } }; console.log(obj1);
你需要初始化obj["test1"] = {}
const obj = {} obj["test1"] = {} obj["test1"]["test1.1"] = 'x' console.log(obj)
var obj = {} _.set(obj, ["test1", "test1.1"], 'x'); console.log(obj)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js"></script>
更實用的方法
const arr = {}; // respecting immutability const rewroteArray = {...arr, da: {"foo": 2}} console.log(rewroteArray);
使用此語法創建對象時, const obj = {}
等於const obj = new Object()
。 您可以使用第二種方法來定義任何級別深度的屬性定義。
const obj = new Object({ "test1": { "test-1":'x' } }); console.log(obj);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.