F
F
fessss2021-09-27 16:38:40
JavaScript
fessss, 2021-09-27 16:38:40

How to overwrite values ​​in nested objects?

There is an object:

const data = {
  name1: {
    blblaDate: '12-31-2021',
    arr: [
      {
        blablaDate: '12-31-2021',
      },
    ],
  },
  name2: {
    blblaDate: '12-31-2021',
    arr: [
      {
        blablaDate: '12-31-2021',
      },
    ],
  },
}

It can be nested as much as you like. We need to find all the keys that contain Dateand change the values: ->

blablaDate: '12-31-2021'blablaDate: '31.12.2021'

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2021-09-27
@fessss

const replaceValues = (val, test, replacer) =>
  val instanceof Array
    ? val.map(n => replaceValues(n, test, replacer))
    : val instanceof Object
      ? Object.fromEntries(Object
          .entries(val)
          .map(([ k, v ]) => [
            k,
            test(k, v)
              ? replacer(v)
              : replaceValues(v, test, replacer)
          ])
        )
      : val;


const newData = replaceValues(
  data,
  k => k.includes('Date'),
  v => v.replace(/(\d+)-(\d+)-/, '$2.$1.')
);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question