我正在为公司制作一个编辑表单,我的团队中有人决定在没有征求其他团队成员意见的情况下更改我们的API负载返回格式,现在我们正在努力追赶。
由于我们需要将值回传到数据库的API调用没有设置为嵌套对象,我需要将其展平以便于操作值并提交。
这是新的嵌套结构:
{
"status": 1,
"data" : {
"name": "Tank",
"dimensions": "2.0 x 2.5 x 4.0"
}
}
我需要将其转换回像这样的结构:
{
"status": 1,
"name": "Tank",
"dimensions": "2.0 x 22.5 x 4.0"
}
我在网上找到了多种解决方案,但它们都给我报了相同的TypeScript错误:
“for (... in ...) 语句必须使用 if 语句进行过滤”
我还发现很多解决方案都在嵌套元素的前面嵌入了第一个元素的名称,像这样:
{
"status": 1,
"data.name": "Tank",
"data.dimensions": "2.0 x 22.5 x 4.0"
}
有人可以给我展示如何重写这个展平函数,以消除TS错误并且不将第一级元素的名称附加到其嵌套元素上,使我得到一个简单的单层对象吗?
这是我的展平函数:
const obj = values;
const flattenObj = (ob) => {
// 包含最终结果的对象
const result = {};
// 遍历对象“ob”
for (const i in ob) {
// 使用typeof()函数检查i的类型,并递归调用函数
if ((typeof ob[i]) === 'object' && !Array.isArray(ob[i])) {
const temp = flattenObj(ob[i]);
for (const j in temp) {
// 将temp存储在result中
result[i + '.' + j] = temp[j];
}
}
// 否则直接将ob[i]存储在result中
else {
result[i] = ob[i];
}
}
return result;
};
console.log(flattenObj(ob)); Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
你可以将
for (const i in ob) { .. }改成
for (const [i, obi] of Object.entries(ob)) { // use obi instead of ob[i] }这样你完全不会触碰原型的内容。