-1

I tried to trim in an object inside objects but it's not working. anyone give the example code trim in an object inside the object.

Example

const data = {tgg:" egg ",ggg:{dfgf:" tyt "}, ff:[{tyuyy:" sd f "}]}

how to trim this object in all scenario

Excepted Output

 {tgg:"egg",ggg:{dfgf:"tyt"}, ff:[{tyuyy:"sd f"}]}

Only remove first and back space

hari prasanth
  • 716
  • 1
  • 15
  • 35

2 Answers2

1

You could loop through the entries of object. If the current value is an object, recursively call the function on the value. If the current value is a string, trim it. This will work for any level of nesting.

const data = {
  tgg: " egg ",
  ggg: {
    dfgf: " tyt "
  },
  ff: [{
    tyuyy: " sd f "
  }]
}

function customTrim(o) {
  for (const [k, v] of Object.entries(o)) {
    if (Object(v) === v)
      customTrim(v)
    else if (typeof v === 'string')
      o[k] = v.trim();
  }
  return o;
}

console.log(customTrim(data))
adiga
  • 34,372
  • 9
  • 61
  • 83
0

const data = {
  tgg: " egg ",
  ggg: {
    dfgf: " tyt "
  },
  ff: [{
    tyuyy: " sdf "
  }]
};

const _data = JSON.stringify(data).replace(/"\s+|\s+"/g, '"');
console.log(JSON.parse(_data));
Tony
  • 894
  • 4
  • 19