如何将Firebase返回的对象转换为指定格式的数组?
将Firebase返回对象转换为指定格式数组
需求说明
需要把Firebase返回的对象转换成如下结构的数组:
原对象格式
{ 0: { first: "https://google.com", last: "google" } }
目标数组格式
[ { first: "https://google.com", last: "google" } ]
尝试的代码
var res = Object.keys(alllinks).reduce((acc, elem)=>{ return { first : alllinks[elem].first, last : alllinks[elem].last }; },{});
Firebase数据获取方式
get(child(dbRef, `links/${dummy.prefix}/links/links`)).then((snapshot) => { if (snapshot.exists()) { const dummy = snapshot.val(); setAlllinks(dummy) } else { console.log("No data available"); } }).catch((error) => { console.error(error); });
问题分析与解决方案
你当前的reduce写法存在逻辑错误:初始值设为空对象{},且每次迭代返回单个对象,导致最终结果只会保留最后一个元素,无法形成数组。以下是两种简洁的正确实现方式:
方法1:使用Object.values + map(推荐)
Object.values直接提取对象的所有值组成数组,再通过map确保输出结构符合需求:
const res = Object.values(alllinks).map(item => ({ first: item.first, last: item.last }));
方法2:修正reduce写法
将初始值改为空数组[],每次迭代把新对象推入数组并返回:
const res = Object.keys(alllinks).reduce((acc, elem) => { acc.push({ first: alllinks[elem].first, last: alllinks[elem].last }); return acc; }, []);
结合Firebase数据获取的完整示例
直接在数据获取完成后执行转换:
get(child(dbRef, `links/${dummy.prefix}/links/links`)).then((snapshot) => { if (snapshot.exists()) { const dummyData = snapshot.val(); const linksArray = Object.values(dummyData).map(item => ({ first: item.first, last: item.last })); setAlllinks(linksArray); } else { console.log("No data available"); } }).catch((error) => { console.error(error); });
内容的提问来源于stack exchange,提问作者like who
相关产品推荐
相关产品推荐

