Search code examples
javascriptvue.jsobjectassign

Assign value of object and nested object in JavaScript


So, basically, I have this object (in vue data()):

...
detail: {
  title: 'I have no idea',
  date: 2020-02-12,
  sender: {
    name: 'John Cenna',
    username: 'john10'
  },
  receipent: {
    name: 'Katleen',
    username: 'katmeow'
  },
  ....
}

Now, I want to assign all of them to be null (for validation process, kind of) but couldn't assign the nested object (the object without child is fine with just loop). How do I do this? thank you


Solution

  • A recursive solution:

    1. Use Object.entries() to iterate the key-value entries of the object as follows. Note that Object.entries() returns an empty array for non-objects.
    2. If the entry's value is already null or undefined, return.
    3. If the entry's value is an array, recurse on each array item (go to step 1 with the array item as the new object to evaluate).
    4. If the entry's value is an object, recurse on the object.
    5. Otherwise, set the entry's value to null.

    const data = {
      detail: {
        title: 'I have no idea',
        date: 2020 - 02 - 12,
        sender: {
          name: 'John Cenna',
          username: 'john10'
        },
        receipent: {
          name: 'Katleen',
          username: 'katmeow'
        },
        items: [
          { id: 100, name: 'Apple' },
          { id: 200, name: 'Banana' },
          { id: 300, name: 'Orange' },
        ]
      }
    }
    
    function nullify(obj) {
      // 1
      Object.entries(obj).forEach(([k,v]) => {
        // 2
        if (v === null || v === undefined) {
          return
        }
        // 3
        if (Array.isArray(v)) {
          return v.forEach(nullify)
        }
    
        // 4
        if (typeof v === 'object') {
          nullify(obj[k])
        } else {
          // 5
          obj[k] = null
        }
      })
    }
    
    nullify(data.detail)
    console.log('res', data.detail)