Eliminate TypeScript errors when flattening nested objects
P粉388945432
P粉388945432 2024-01-10 18:05:39
0
1
605

I'm making an edit form for my company and someone on my team decided to change our API payload return format without consulting other team members, and now we're trying to catch up.

Since the API call we need to pass the value back to the database is not set up as a nested object, I need to flatten it to make it easier to manipulate the value and submit it.

This is the new nested structure:

{
       "status": 1, 
       "data" : {
            "name": "Tank",
            "dimensions": "2.0 x 2.5 x 4.0"
       }
    }

I need to convert it back to a structure like this:

{
       "status": 1, 
       "name": "Tank",
       "dimensions": "2.0 x 22.5 x 4.0"
    }

I found multiple solutions online, but they all gave me the same TypeScript error:

"The for (... in ...) statement must be filtered using an if statement"

I also found that many solutions embed the name of the first element in front of the nested elements, like this:

{
       "status": 1, 
       "data.name": "Tank",
       "data.dimensions": "2.0 x 22.5 x 4.0"
    }

Can someone show me how to rewrite this flatten function to eliminate the TS error and not append the first level element's name to its nested elements so that I get a simple single level object?

This is my flattening function:

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));

P粉388945432
P粉388945432

reply all(1)
P粉976737101

You can change

for (const i in ob) { .. }

changed to

for (const [i, obi] of Object.entries(ob)) { // use obi instead of ob[i] }

This way you will not touch the content of the prototype at all.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template