Rog*_*gie 10 javascript arrays json object
我从GET API调用Firebase数据库得到以下响应.它是嵌套的JSON对象.
我想name使用JavaScript将每个嵌套对象的键的所有值都放到一个数组中
获取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”
}
}
Run Code Online (Sandbox Code Playgroud)
它可以使用:
使用Array.reduce于累积name值成一个单一的阵列.
使用Object.keys和Array.map迭代键并将其映射到name数组.
使用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);Run Code Online (Sandbox Code Playgroud)