You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 05:35:11