gpt4 book ai didi

javascript - 从 Firebase 响应嵌套的 JSON 对象获取键/值对

转载 作者:可可西里 更新时间:2023-11-01 02:37:28 25 4
gpt4 key购买 nike

我从对 Firebase 数据库的 GET API 调用中得到以下响应。它是一个嵌套的 JSON 对象。

我想使用 JavaScript 将每个嵌套对象中键 name 的所有值放入一个数组中

获取 REST API 响应:

{
"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”
}
}

最佳答案

可以使用:

  1. 使用 Array.reduce name 值累积到一个数组中。

  2. 使用 Object.keys Array.map 遍历键并将其映射到 name 数组。

  3. 使用 Object.values Array.map

  4. 使用 Array.from 并利用第二个映射函数参数将单个对象映射到 names 数组。

const 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"}};

//using Object.values & reduce
let name = Object.values(obj).reduce((acc, ele) =>{
return acc.concat(ele.name)
}, []);
console.log(name);

//using Object.keys & map
name = Object.keys(obj).map((ele) => obj[ele]['name']);
console.log(name);

//using Object.values & map
name = Object.values(obj).map((ele) => ele.name);
console.log(name);

//using Array.from
name = Array.from(Object.values(obj), ele => ele.name);
console.log(name);

关于javascript - 从 Firebase 响应嵌套的 JSON 对象获取键/值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54683006/

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