如何将Supabase返回的对象数组转换为指定结构的对象?
解决方案
你需要将数组中的每个对象转换为目标对象的键值对,以下两种方法都可以实现:
方法1:使用Array.reduce()构建对象
这是处理数组转对象的经典方法,通过累加器逐步构建目标结构:
const weatherData = data.reduce((acc, item) => { // 将weather作为键,percentage转为数字后作为值 acc[item.weather] = Number(item.percentage); return acc; }, {}); // 初始值设为空对象
方法2:使用Object.fromEntries()(更简洁)
先通过map将每个对象转为[键, 值]的数组,再用Object.fromEntries直接转换为对象:
const weatherData = Object.fromEntries( data.map(item => [item.weather, Number(item.percentage)]) );
整合到你的Supabase异步函数中
完整的函数代码如下:
async function getData() { const { data, error } = await supabase .from('cities') .select('weather, percentage') .match({ city: targetCity }); if (error) throw new Error(error.message); // 二选一即可 const weatherData = data.reduce((acc, item) => { acc[item.weather] = Number(item.percentage); return acc; }, {}); // 或者用这个 // const weatherData = Object.fromEntries(data.map(item => [item.weather, Number(item.percentage)])); return weatherData; }
补充说明
你之前用data.map(Object.values)得到的是二维数组,这是因为map只会对数组的每个元素做转换并返回新数组,而不会帮你把数组转为对象。上面两种方法都是在map的基础上(或直接用reduce)完成了数组到对象的转换,同时还把字符串类型的percentage转为了数字类型,匹配你需要的目标结构。
内容的提问来源于stack exchange,提问作者mjschwan
相关产品推荐
相关产品推荐

