-1

I'm trying to remove the extra space inside of the object value.

const object = {
    primaryInformation: {
       firstName: "John  Doe",
       lastName: "Doe     Space"
    }
}

Is there any simplest way to remove the extra space between the words of object value using map?

Expected Output

firstName: "John Doe",
lastName: "Doe Space" 
Dave
  • 9
  • 1
  • 6
  • I'm trying to remove the space using object not a single string. Is there any chance that we can map all object value then remove the string? – Dave Apr 26 '22 at 15:43
  • 1
    The field in the object is still a string, you can apply a string replace code while doing a `.map` assuming you have an array of objects – Anurag Srivastava Apr 26 '22 at 15:44
  • @Dave not with `Array.prototype.map`, since that's just a function for arrays – Samathingamajig Apr 26 '22 at 15:44
  • You can recursively go through every nested layer of the object – Samathingamajig Apr 26 '22 at 15:45
  • Combine [this](https://stackoverflow.com/questions/36467369/looping-through-an-object-and-changing-all-values) with [the duplicate question](https://stackoverflow.com/questions/1981349/regex-to-replace-multiple-spaces-with-a-single-space) and you should be fine. If it doesn't work, you can [edit] your question showing how you're trying to combine them. – 0stone0 Apr 26 '22 at 15:45

1 Answers1

0

Based on the object structure in your question, I've written this loop.

const object = {
  primaryInformation: {
    firstName: "John  Doe",
    lastName: "Doe     Space"
  }
};

for (const key in object) {
  const value = object[key];

  for (const key2 in value) {
    const string = value[key2];

    value[key2] = string.replace(/  +/g, " ");
  }
}

console.log(object);
Inder
  • 1,711
  • 1
  • 3
  • 9