gpt4 book ai didi

javascript - 如何找到正确的 Json 对象

转载 作者:行者123 更新时间:2023-11-29 20:01:55 26 4
gpt4 key购买 nike

我是 Json 的新手,正在尝试加载 Json 对象的一部分。结构是:

{
"Monday": {
"title": "Magic Monday",
"text": "On Magic Monday, all the food disappears.",
"image": "images/special.jpg",
"color": "red"
},

"Tuesday": {
"title": "Twofer Tuesday",
"text": "Two vegetables for the price of one!.",
"image": "images/special.jpg",
"color": "green"
}
}

我有一个变量 weekDay,我将使用它来查找正确的对象。找到后,我想在我的 HTML 中使用 title 和 text 的值。

到目前为止我有代码:

$.getJSON('data/specials.json', function (data) {
$.each(data, function (entryIndex, entry) {
var html = '<h4>' + entry['title'] + '</h4>';
html += '<p>' + entry['text'] + '</p>';
$('#details').append(html);
});
});

但我不知道,如何只从具有正确工作日的对象中获取标题和文本。

提前致谢:)

最佳答案

如果你有

var weekDay = "Tuesday";

那么你可以简单地使用

var entry = data[weekDay];

然后

var title = entry.title;

var title = entry['title'];

This document说明您如何访问对象属性。

关于javascript - 如何找到正确的 Json 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13974741/

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