-1

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?

3
  • 1
    Why can't you think of a way to iterate recursively? Just write a recursive function. I don't think lodash has functions that recurse. Commented Nov 14, 2022 at 21:38
  • See here for an example. Commented Nov 14, 2022 at 21:41
  • Related: Javascript - Set all values in nested object to null. Commented Nov 14, 2022 at 21:42

3 Answers 3

2

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!

Sign up to request clarification or add additional context in comments.

5 Comments

This will turn null values into empty objects...
yes I assume there are no null values
@BenBorchard added an extra guard so it'll check for null
Floats don't get changed to 0
fixed it, I'm not really sure about the data structure.
2

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

1 Comment

Because of early returns, you don't actually need else if, only if.
2

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
}

1 Comment

This will turn null values into empty objects...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.