結構:
stockTagList: { [key]: { name: "Default" } }
其中 [key]代表是變數,若沒有[],則key就是字串key
內容:
stockTagList: {
abc: { name: "Default" },
xyz: { name: "Tech" },
test: { name: "Finance" }
}
讀取所有key和value:
for (const [key, value] of Object.entries(gAppSetting.stockTagList)) {
console.log(key); // abc
console.log(value.name); // Default
}
結果:
key=abc, name=Default
key=xyz, name=Tech
key=test, name=Finance
只取 key:
const keys = Object.keys(stockTagList) 回傳的是陣列
方法1:for...of
for (const key of Object.keys(gAppSetting.stockTagList)) {
console.log(key);
const item = gAppSetting.stockTagList[key];
console.log(item.name);
}
方法2:forEach
Object.keys(gAppSetting.stockTagList).forEach(key => {
console.log(key);
console.log(gAppSetting.stockTagList[key].name);
});
方法3:用 index
const keys = Object.keys(gAppSetting.stockTagList);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
console.log(key);
console.log(gAppSetting.stockTagList[key].name);
}
只取 value:
Object.values(gAppSetting.stockTagList)
方法同上
No comments:
Post a Comment