js 匹配后台返回数据实现动态表头字段?
总的表格表头配置,可以手动新增字段
columns: [{
title: "海区",
key: "area",
}, {
title: "浪高(m)",
key: "waveHeight",
}, {
title: "水温(℃)",
key: "waterTemperature",
}],
接口返回数据如下的时候
0: {area: "刁口", waterTemperature: "-0.4 "}
1: {area: "黄河口", waterTemperature: "-0.1 "}
2: {area: "广利港", waterTemperature: "-0.5 "}
3: {area: "东营港", waterTemperature: "0.2 "}
4: {area: "新户", waterTemperature: "-0.7 "}
5: {area: "埕口", waterTemperature: "-0.4 "}
表格展示海区跟水温就是动态表头,后台返回什么字段,表头配置的 columns 就是什么字段
有什么好的方法吗
回复
1个回答
test
2024-06-23
本质就是对列进行过滤,把有效的列选出来。如果每行数据都是规则的,包含所有列的,那只需要拿第一条数据出来作为条件过滤出列就好,如:
const columns = [
{ title: "海区", key: "area", },
{ title: "浪高(m)", key: "waveHeight", },
{ title: "水温(℃)", key: "waterTemperature", }
];
const data = [
{ area: "刁口", waterTemperature: "-0.4 " },
{ area: "黄河口", waterTemperature: "-0.1 " },
{ area: "广利港", waterTemperature: "-0.5 " },
{ area: "东营港", waterTemperature: "0.2 " },
{ area: "新户", waterTemperature: "-0.7 " },
{ area: "埕口", waterTemperature: "-0.4 " }
];
const columnSet = new Set(Object.keys(data[0]));
const validColumn = columns.filter(({ key }) => columnSet.has(key));
console.log(validColumn);
如果数据是不规则的,或者说,每行数据都只是把有效的属性列出来了,那要找所有列就需要遍历全部数据。
这种情况下就是在数据中每一行的 key 找出来,加到 columnSet 中去,可以用一个 flatMap 处理出来:
// const columnSet = new Set(Object.keys(data[0]));
const columnSet = new Set(data.flatMap(it => Object.keys(it)));
回复
适合作为回答的
- 经过验证的有效解决办法
- 自己的经验指引,对解决问题有帮助
- 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
- 询问内容细节或回复楼层
- 与题目无关的内容
- “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容