gpt4 book ai didi

javascript - 使用 JavaScript 从嵌套 JSON 对象中的值获取上层键?

转载 作者:行者123 更新时间:2023-11-28 14:22:21 24 4
gpt4 key购买 nike

如果我知道下面嵌套 JSON 中键 name 的值 Africola,如何获取其对应的上层键“barID1” ' 在 JavaScript 中?

{
"barID1": {
"address": "4 East Terrace, Sydney NSW 2000",
"appStoreURL": "http://itunes.apple.com/app/idXXXXXXXXX",
"description": “description text”,
"imgURLs": [ "Https:url1”, "https:url2”, "https:url3” ],
"lat": -34.810585,
"lon": 138.616739,
"name": "Africola",
"phone": "(08) 8223 3885",
"status": "active",
"venueImgURL": "https:url”
},
"barID2": {
"address": "138/140 Gouger St, Sydney NSW 2000",
"appStoreURL": "http://itunes.apple.com/app/idXXXXXXXXX",
"description": “description text”,
"imgURLs": [ "Https:url1”, "https:url2”, "https:url3” ],
"lat": -34.848082,
"lon": 138.599813,
"name": "Disco Mexico Taqueria",
"phone": "0416 855 108",
"status": "active",
"venueImgURL": "https:url”
}
}

最佳答案

此处,您的 JSON 格式错误,包含无效字符。在键上使用查找

let obj = {
"barID1": {
"address": "4 East Terrace, Sydney NSW 2000",
"appStoreURL": "http://itunes.apple.com/app/idXXXXXXXXX",
"description": "description text",
"imgURLs": [ "Https:url1", "https:url2", "https:url3" ],
"lat": -34.810585,
"lon": 138.616739,
"name": "Africola",
"phone": "(08) 8223 3885",
"status": "active",
"venueImgURL": "https:url"
},
"barID2": {
"address": "138/140 Gouger St, Sydney NSW 2000",
"appStoreURL": "http://itunes.apple.com/app/idXXXXXXXXX",
"description": "description text",
"imgURLs": [ "Https:url1", "https:url2", "https:url3" ],
"lat": -34.848082,
"lon": 138.599813,
"name": "Disco Mexico Taqueria",
"phone": "0416 855 108",
"status": "active",
"venueImgURL": "https:url"
}
};

let result = Object.keys(obj).find(key => obj[key].name === "Africola");
console.log(result);

作为函数:

let obj = {
"barID1": {
"address": "4 East Terrace, Sydney NSW 2000",
"appStoreURL": "http://itunes.apple.com/app/idXXXXXXXXX",
"description": "description text",
"imgURLs": [ "Https:url1", "https:url2", "https:url3" ],
"lat": -34.810585,
"lon": 138.616739,
"name": "Africola",
"phone": "(08) 8223 3885",
"status": "active",
"venueImgURL": "https:url"
},
"barID2": {
"address": "138/140 Gouger St, Sydney NSW 2000",
"appStoreURL": "http://itunes.apple.com/app/idXXXXXXXXX",
"description": "description text",
"imgURLs": [ "Https:url1", "https:url2", "https:url3" ],
"lat": -34.848082,
"lon": 138.599813,
"name": "Disco Mexico Taqueria",
"phone": "0416 855 108",
"status": "active",
"venueImgURL": "https:url"
}
};

const findKeyByName = (obj, search) => Object.keys(obj).find(key => obj[key].name === search);

console.log(findKeyByName(obj, 'Africola'));
console.log(findKeyByName(obj,'Disco Mexico Taqueria'));

关于javascript - 使用 JavaScript 从嵌套 JSON 对象中的值获取上层键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54798708/

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