gpt4 book ai didi

jquery - 循环嵌套对象

转载 作者:行者123 更新时间:2023-12-01 07:41:39 25 4
gpt4 key购买 nike

找到了该主题的多个线程,但无法解决我的问题。

我有一个像这样的对象:

 allItems: {
item1: {
val1: 4,
val2: 'blaharb'
},
itemxyz2: {
val1: 76,
val2: 'blurb'
}
}

现在我只想列出一个类似的列表

item1 has 4 for val1 and blaharb for val2
itemxyz2 has 76 for val1 and blurb for val2

到目前为止我的尝试:

console.log(allItems.item1.val1); // prints correctly '4' in the console

$.each(allItems, function(key, value) {
console.log(key); // gives me correct key (like 'item1')
console.log(allItems.item1.val1);// error: "undefined is not an object" - but why?!
console.log(allItems.key.val1); // same error, understandable ...
});

非常感谢您的帮助,谢谢!

最佳答案

您可以使用数组语法访问对象属性:

$.each(allItems, function(key, value) {
console.log(allItems[key]["val1"]);
console.log(allItems[key]["val2"]);
});

示例:

var allItems = {
item1: {
val1: 4,
val2: 'blaharb'
},
itemxyz2: {
val1: 76,
val2: 'blurb'
}
};


$.each(allItems, function(key, value) {
console.log(allItems[key]["val1"]);
console.log(allItems[key]["val2"]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

关于jquery - 循环嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46697792/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com