deep replace

by Christian Gambardella

HTML

<div id="result">
</div>

JavaScript

const doc = {
  id: 1,
  name: 'foo',
  body: 'yoyoyo',
  created_at: '2018-01-03T16:11:54.000Z',
  updated_at: '2018-01-03T16:11:54.000Z',
  images: [
    {
      id: 2,
      created_at: '2018-01-03T16:11:54.000Z',
      updated_at: '2018-01-03T16:11:54.000Z'
    },
    {
      id: 3,
      created_at: '2018-01-03T16:11:54.000Z',
      updated_at: '2018-01-03T16:11:54.000Z'
    }
  ]
}

function addUnixTimestamp (data) {
	const newData = JSON.parse(JSON.stringify(data))
  Object.keys(data).forEach(attribute => {
    const value = data[attribute]
		switch (value.constructor) {
      case Array:
        newData[attribute] = value.map(entry => addUnixTimestamp(entry))
        break

			case Object:
        newData[attribute] = addUnixTimestamp(value)
        break

      default:
        const match = attribute.match(/([a-zA-Z-_]+_at)$/)
        if (match) {
        	const unix = Math.round((new Date(value)).getTime() / 1000)
          newData[match[0] + '_unix'] = unix
        }
    }
  })
  return newData
}

const result = JSON.stringify(addUnixTimestamp(doc))

document.querySelector('#result').textContent = result