我有一个对象文字或类似json文件,其中包含数据,我想要的是将SMBPremium和MAX数据包装在一个数组中,以便我可以通过访问其索引来定位。如何将对象文字修改为数组,以便我可以定位SMBPremium和MAX。有点像这样。
var productMap = {
"TEC0": {
"SMBPremium" : {
"productName": "Wilson",
"panelClass": "WilsonClass",
"fullinfoClass": "Wilsonfull",
"productPageLink": "",
"panelPageLinkGA": "",
"fullPageLinkGA": "",
"notifLinkDanger" : {
"linkPrimary" : "",
"linkSecondary" : ""
},
"notifLinkRed" : {
"linkPrimary" : "",
"linkSecondary" : ""
},
"notifLinkInfo" : "",
"notifLinkWarning" : "",
"notifLinkSuccess" : ""
},
"MAX": {
"productName": "Spalding",
"panelClass": "spalding",
"fullinfoClass": "spalding",
"productPageLink": "",
"panelPageLinkGA": "",
"fullPageLinkGA": "",
"notifLinkDanger" : {
"linkPrimary" : "",
"linkSecondary" : ""
},
"notifLinkRed" : {
"linkPrimary" : "",
"linkSecondary" : ""
},
"notifLinkInfo" : "",
"notifLinkWarning" : "",
"notifLinkSuccess" : ""
}
}
};
这是我的json
{{1}}
答案 0 :(得分:2)
使用 array.map 进行转换:
productMap2 = {};
productMap2.TEC0 = Object.keys(productMap['TEC0']).map(key => productMap['TEC0'][key]);
然后,您可以访问每个元素的 productName 属性:
productMap2.TEC0[1].productName
答案 1 :(得分:1)
试试这个
index = 1
productMap['TEC0'][Object.keys(productMap['TEC0'])[index]].productName;
<强> 解释 强>
productMap [&#39; TEC0&#39;]是一个json对象
Object.keys(productMap [&#39; TEC0&#39;]) - 将json对象键作为数组返回。 在这个例子中像这样[&#34; SMBPremium&#34;,&#34; MAX&#34;]
Object.keys(productMap [&#39; TEC0&#39;])[index] - 将返回基于姓名的名称
索引通过。
productMap [&#39; TEC0&#39;] [key_name] - 将基于json对象获取
key_name来自以前的状态。
答案 2 :(得分:1)
您可以按照自己的意愿重新创建对象productMap:
// Every object is a map:
var tec0 = productMap['TEC0'];
var keys = Object.keys(tec0);
var array = [];
for(var i=0; i<keys.length; i++) {
var key = keys[i];
var value = tec0[key];
array.push(value);
}
var newProductMap = {'TEC0': array};
alert(newProductMap['TEC0'][1].productName);
注意:Faly的答案要优雅得多。请注意浏览器与箭头功能的兼容性(IE不支持)。
同意Ammar的答案,IE不支持。
答案 3 :(得分:1)
使用Object.values()方法:
productMap["TEC0"] = Object.values(productMap["TEC0"]);
答案 4 :(得分:0)
您可以将项目映射到所需密钥数组的索引。
var productMap = { TEC0: { SMBPremium: { productName: "Wilson", panelClass: "WilsonClass", fullinfoClass: "Wilsonfull", productPageLink: "", panelPageLinkGA: "", fullPageLinkGA: "", notifLinkDanger: { linkPrimary: "", linkSecondary: "" }, notifLinkRed: { linkPrimary: "", linkSecondary: "" }, notifLinkInfo: "", notifLinkWarning: "", notifLinkSuccess: "" }, MAX: { productName: "Spalding", panelClass: "spalding", fullinfoClass: "spalding", productPageLink: "", panelPageLinkGA: "", fullPageLinkGA: "", notifLinkDanger: { linkPrimary: "", linkSecondary: "" }, notifLinkRed: { linkPrimary: "", linkSecondary: "" }, notifLinkInfo: "", notifLinkWarning: "", notifLinkSuccess: "" } } },
keys = ['SMBPremium', 'MAX'];
keys.forEach((k, i) => productMap.TEC0[i] = productMap.TEC0[k]);
console.log(productMap['TEC0'][0].productName);