我正在为我的公司制作一个编辑表单,我的团队中的某人决定更改 API 有效负载返回的格式,而没有咨询团队的其他成员,现在我们正在迎头 catch 。
由于我们必须将调用的 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 语句进行过滤”
我还看到很多人都将第一个元素的名称嵌入到其嵌套元素的 from 中,如下所示:
{
"status": 1,
"data.name": "Tank",
"data.dimensions": "2.0 x 22.5 x 4.0"
}
有人可以告诉我如何重写这个扁平化函数,它可以消除 TS 错误,并且不会将第一级元素的名称附加到其嵌套元素中,从而给我留下简单的单级对象吗?
这是我的展平函数:
const obj = values;
const flattenObj = (ob) => {
// The object which contains the final result
const result = {};
// loop through the object "ob"
for (const i in ob) {
// We check the type of the i using typeof() function and recursively call the function again
if ((typeof ob[i]) === 'object' && !Array.isArray(ob[i])) {
const temp = flattenObj(ob[i]);
for (const j in temp) {
// Store temp in result
result[i + '.' + j] = temp[j];
}
}
// Else store ob[i] in result directly
else {
result[i] = ob[i];
}
}
return result;
};
console.log(flattenObj(ob));
最佳答案
你可以改变
for (const i in ob) { .. }
至
for (const [i, obi] of Object.entries(ob)) { // use obi instead of ob[i] }
这样你就根本不会接触原型(prototype)的东西。
关于javascript - 展平嵌套对象而不出现 TS 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76854672/