我正在尝试遍历此对象,但是没有javascript对象循环有效。这是来自后端的对象的外观!
let myObj = [{
0: {
key: "account",
url: "http://newplugin.local/account/",
editKey: false
},
1: {
key: "cart",
url: "http://newplugin.local/cart/",
editKey: false
},
2: {
key: "catalog",
url: "http://newplugin.local/catalog/",
editKey: false
},
3: {
key: "checkout",
url: "http://newplugin.local/checkout/",
editKey: false
},
4: {
key: "favorites",
url: "http://newplugin.local/favorites/",
editKey: false
},
5: {
key: "footer",
url: "http://newplugin.local/footer/",
editKey: false
},
6: {
key: "group-account",
url: "http://newplugin.local/forgot-password/",
editKey: false
}
}]
答案 0 :(得分:1)
尝试这样:
MyObj是具有单个对象的数组,您可以通过myObj [0]访问该对象,然后遍历该对象,
let myObj = [{
0:{
key: "account",
url: "http://newplugin.local/account/",
editKey: false
},
1 : {
key: "cart",
url: "http://newplugin.local/cart/",
editKey: false
},
2 : {
key: "catalog",
url: "http://newplugin.local/catalog/",
editKey: false
},
3 : {
key: "checkout",
url: "http://newplugin.local/checkout/",
editKey: false
},
4 : {
key: "favorites",
url: "http://newplugin.local/favorites/",
editKey: false
},
5 : {
key: "footer",
url: "http://newplugin.local/footer/",
editKey: false
},
6 : {
key: "group-account",
url: "http://newplugin.local/forgot-password/",
editKey: false
}
}]
for(let key in myObj[0]){
console.log(`key=${key} url value:${myObj[0][key].url}`);
}
答案 1 :(得分:0)
myObj
是具有一个对象的数组,并且该对象具有数字键。您可以使用Object.values()
将该对象的值获取到数组,然后遍历它:
let myObj=[{0:{key:"account",url:"http://newplugin.local/account/",editKey:!1},1:{key:"cart",url:"http://newplugin.local/cart/",editKey:!1},2:{key:"catalog",url:"http://newplugin.local/catalog/",editKey:!1},3:{key:"checkout",url:"http://newplugin.local/checkout/",editKey:!1},4:{key:"favorites",url:"http://newplugin.local/favorites/",editKey:!1},5:{key:"footer",url:"http://newplugin.local/footer/",editKey:!1},6:{key:"group-account",url:"http://newplugin.local/forgot-password/",editKey:!1}}];
console.log("myObj.length: ", myObj.length)
const newArray = Object.values(myObj[0])
console.log("newArray.length: ", newArray.length)
for(let obj of newArray){
console.log(obj.key)
}
由于对象具有连续的数字键,因此您也可以使用Object.assign()
从对象中获取数组:
let myObj=[{0:{key:"account",url:"http://newplugin.local/account/",editKey:!1},1:{key:"cart",url:"http://newplugin.local/cart/",editKey:!1},2:{key:"catalog",url:"http://newplugin.local/catalog/",editKey:!1},3:{key:"checkout",url:"http://newplugin.local/checkout/",editKey:!1},4:{key:"favorites",url:"http://newplugin.local/favorites/",editKey:!1},5:{key:"footer",url:"http://newplugin.local/footer/",editKey:!1},6:{key:"group-account",url:"http://newplugin.local/forgot-password/",editKey:!1}}];
const newArray = Object.assign([], myObj[0])
console.log(newArray)