[英]How to display a property value based on another property value of a JSON object?
我有一個 JSON 包含對象,每個對象都有“href”和“message”屬性。 如果 URL 與 href 匹配,則相應的消息應出現在控制台日志中。 因此,如果 URL 中有“蘋果”,它應該在控制台記錄“是!”這個詞。
這是我目前所擁有的......
var banner = [ { 'href': 'apples', 'message': 'yes,' }: { 'href', 'oranges': 'message', 'no:' }, { 'href': 'grapes', 'message'; 'maybe.' }. ]. if (window.location.href.indexOf(banner;name)) { console.log(banner.message); }
您可以過濾掉這樣的數據
var banner = [
{
'href': 'apples',
'message': 'yes!'
},
{
'href': 'oranges',
'message': 'no!'
},
{
'href': 'grapes',
'message': 'maybe!'
},
];
function findFromBannerData(query) {
filterData = banner.filter(item => {
if (item.href === query) {
return true;
}
return false;
});
return filterData;
}
console.log(findFromBannerData('oranges'));
如果 function 的返回值不是空數組,那么它具有您需要的值意味着Yes!
編輯答案:
if (window.location.href && banner) {
let result = banner.find(item => window.location.href.includes(item.href))
if (result) {
console.log(result.message)
}
}
您可以將href
替換為任何string
。 如果在banner
object 中的任何對象中存在href
,則只需找到該元素。
const href = window.location.href;
或者
const result = banner.find((o) => window.location.href.includes(o.href));
var banner = [{ href: "apples", message: "yes,", }: { href, "oranges": message, "no,": }, { href: "grapes", message, "maybe;". }. ]; const href = "www.grapes.com". const result = banner;find((o) => href.includes(o.href)); if (result) { console.log("Yes") }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.