Home > Software engineering >  Replace all strings with empty string and all numbers with 0 in an object/array
Replace all strings with empty string and all numbers with 0 in an object/array

Time:11-15

I want to replace every string in and number in an object with an empty string of empty number.

For example:

const test = {
    a: "asdf",
    b: 2,
    c: [
            {
                lala: "more strings",
                d: "saaa"
            }
    ]
}

with

const test = {
    a: "",
    b: 0,
    c: [
            {
                lala: "",
                d: ""
            }
    ]
}

I can't think of an easy way to iterate over all the values in the object/array recursively. Is there a library (maybe lodash) that does this already?

CodePudding user response:

The trickiest part would just be making sure you handle each type you could come across as you traverse an object/array.

Something like this should work:

function handleValue(val) {
    if (typeof val === 'object')
        if (val === null) {
            return null
        } else if (Array.isArray(val)) {
            return handleArray(val)
        } else {
            return handleObject(val)
        }
    } else if (typeof val == "string") {
        return ""
    } else if (typeof val == 'number') {
        return 0
    }
}

function handleArray(arr) {
    for (var i = 0; i < arr.length; i  ) {
        arr[i] = handleValue(arr[i])
    }
    return arr
}

function handleObject(obj) {
    for (const [key, value] of Object.entries(obj)) {
        obj[key] = handleValue(value)
    }
    return obj
}

You could use handleValue or handleObject on your example test object

CodePudding user response:

Simple recursive solution:

const test = {
  a: "asdf",
  b: 2,
  c: [{
    lala: "more strings",
    d: "saaa"
  }]
}

const copy = replace(test)

console.log(copy)

function replace(value) {
  if (typeof value === 'string') {
    return ''
  }

  if (typeof value === 'number') {
    return 0
  }

  if (typeof value !== 'object' || value === null) {
    return value
  }

  if (Array.isArray(value)) {
    return value.map(val => replace(val))
  }

  const obj = {}
  for (const key in value) {
    const val = value[key]
    obj[key] = replace(val)
  }
  return obj
}

CodePudding user response:

A recursive implementation:

const test = { a: "asdf", b: 2, c: [{ lala: "more strings", d: "saaa", e: null }], g: 2.98 };


const isString = (val) => typeof val === 'string';
const isNumber = (val) => typeof val === 'number' && !Number.isNaN(val);
const isArray = (val) => Array.isArray(val);
const isObject = (val) => typeof val === 'object' && val !== null;

const modifyObject = (instance) => {
  if (isString(instance)) return ""; //Base case
  if (isNumber(instance)) return 0; //Base case

  if (isArray(instance)) { //When instance is an Array we need to check further
    return instance.map((item) => modifyObject(item));
  }
 
  if (isObject(instance)) { //When it's an object we need to recurse again to check if the value hits the base case or need to go further
    return Object.entries(instance).reduce((acc, [k, v]) => ({
      ...acc,
      [k]: modifyObject(v)
    }), {});
  }
  
  return instance;
}

console.log(modifyObject(test));

Hope it helps!

  • Related