Skip to content
Advertisement

Prefix a string to json key in javascript

I would like to prefix ‘d:’ before the key of the json object , how can i do that

json data

"data": {
   "aa": "value",
   "ab": "value"
  }

Expected result :

"d:data": {
   "d:aa": "value",
   "d:ab": "value"
  }

Advertisement

Answer

Like this:

let foo = { "data": {
   "aa": "value",
   "ab": "value"
  }
}

function prefixObj(obj, prefix) {
    return Object.fromEntries(Object.entries(obj).map(([key, value]) => {
        return [`${prefix}${key}`, typeof value === 'object' ? prefixObj(value, prefix) : value];
    }));
}

console.log(prefixObj(foo, 'd:'))
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement