find the json path for a specific value using javascript - javascript

how to find the json path for a specific value using javascript
var data = {
key1: {
children: {
key2:'value',
key3:'value',
key4: value
},
key5: 'value'
}
expected result from the above data.key1.children.key3
Any help would be appreciated.

var str = "key3";
data["key1"]["children"][str];

This function returns all available paths in your(any) object:
Using this function you can get
["key1.children.key2", "key1.children.key3", "key1.children.key4", "key1.key5"]
function allPaths(root) {
let stack = [];
let result = [];
// checks if object
const isObject = value => typeof value === "object";
stack.push(root);
while (stack.length > 0) {
let node = stack.pop();
if (isObject(node)) {
Object.entries(node).forEach(([childNodeKey, childNodeValue]) => {
if (isObject(childNodeValue)) {
const newObject = Object.fromEntries(
Object.entries(childNodeValue).map(([cnk, cnv]) => {
return [`${childNodeKey}.${cnk}`, cnv];
})
);
stack.push(newObject);
} else {
stack.push(`${childNodeKey}`);
}
})
} else {
result.push(node);
}
}
return result.reverse();
}
Let me know in the comments if it was helpful for you

Related

Trying to extract common functionality among these

I have below method where i am using reducer to set these dictionaries "earliestOptionByInitialRevision" and "latestOptionByInitialRevision" inside the reducer and the code is looks like as below
const lookups = optionsInput?.reduce(
(acc, option) => {
const [optionById, earliestOptionByInitialRevision, latestOptionByInitialRevision] = acc;
optionById[option.id] = option;
const isCustomProject = option.initialRevisionId === null || option.initialRevisionId === undefined;
if (
isCustomProject ||
!earliestOptionByInitialRevision[option.initialRevisionId] ||
option.revision < earliestOptionByInitialRevision[option.initialRevisionId].revision
) {
// trying to extract the below into common
//function because in below if condition i have used the same and difference is
// "earliestOptionByInitialRevision"
if (isCustomProject) {
option = {...option, initialRevisionId:'customProjectOption'}
if (!earliestOptionByInitialRevision[option.initialRevisionId])
{
earliestOptionByInitialRevision[option.initialRevisionId] = [option];
} else {
earliestOptionByInitialRevision[option.initialRevisionId].push(option);
}
} else {
earliestOptionByInitialRevision[option.initialRevisionId] = option;
}
}
if (
isCustomProject ||
!latestOptionByInitialRevision[option.initialRevisionId] ||
option.revision > latestOptionByInitialRevision[option.initialRevisionId].revision
) {
// the below if condition same as with above and the difference
// is "latestOptionByInitialRevision"
if (isCustomProject) {
option = {...option, initialRevisionId:'customProjectOption'}
if (!latestOptionByInitialRevision[option.initialRevisionId]) {
latestOptionByInitialRevision[option.initialRevisionId] = [option];
} else {
latestOptionByInitialRevision[option.initialRevisionId].push(option);
}
} else {
latestOptionByInitialRevision[option.initialRevisionId] = option;
}
}
return acc;
},
[{}, {}, {}]
) ?? [{}, {}, {}];
const [optionById, earliestOptionByInitialRevision, latestOptionByInitialRevision] = lookups;
i would like to extract the below common functionality but could not be able to get through on how to achieve the same. Could any one please help on this that would be very grateful to me
if (isCustomProject) {
option = {...option, initialRevisionId:'customProjectOption'}
if (!earliestOptionByInitialRevision[option.initialRevisionId]) {
earliestOptionByInitialRevision[option.initialRevisionId] = [option];
} else {
earliestOptionByInitialRevision[option.initialRevisionId].push(option);
}
} else {
earliestOptionByInitialRevision[option.initialRevisionId] = option;
}
Many thanks in advance
update:
A quick fix could be to extract the common functionality into a function, parameterised by the dict (JavaScript object).
const optionsInput = [{
id: 1,
revision: 2
},
{
id: 2,
revision: 1
},
];
const lookups = optionsInput?.reduce(
(acc, option) => {
const [optionById, earliestOptionByInitialRevision, latestOptionByInitialRevision] = acc;
optionById[option.id] = option;
const isCustomProject = option.initialRevisionId === null || option.initialRevisionId === undefined;
const updateDict = (dict) => {
if (isCustomProject) {
const newOption = {...option, initialRevisionId:'customProjectOption'}
if (!dict[option.initialRevisionId]) {
dict[option.initialRevisionId] = [newOption];
} else {
dict[option.initialRevisionId].push(newOption);
}
} else {
dict[option.initialRevisionId] = option;
}
};
if (isCustomProject || !earliestOptionByInitialRevision[option.initialRevisionId] || option.revision < earliestOptionByInitialRevision[option.initialRevisionId].revision) {
updateDict(earliestOptionByInitialRevision);
}
if (isCustomProject || !latestOptionByInitialRevision[option.initialRevisionId] || option.revision > latestOptionByInitialRevision[option.initialRevisionId].revision) {
updateDict(latestOptionByInitialRevision);
}
return acc;
},
[{}, {}, {}]
) ?? [{}, {}, {}];
console.log(lookups);

How to change the object depending value type javascript?

How to change the nested object to new object in javascript.
I have a object obj in which if details is arrays, then take first array value as value in javascript.
function newObj(obj1) {
let map = {};
obj1.forEach(e => {
let details = e.details;
Object.values(details).forEach(value => {
if (Array.isArray(value) && value.length > 0) {
map[value[0]] = value[0];
}
else if (typeof value === 'object') {
Object.values(value).forEach(val => { map[val] = val; });
}
})
});
return map;
}
var obj1 = [
{
details : {
"info" : ["stocks", "finance", ""],
"sales" : ["analytics"]
}
}
];
var obj2 = [
{
details : {
"city" : "SG"
}
}
];
var r1 = this.newObj(obj1);
var r2 = this.newObj(obj2);
Expected Output
//for obj1 (show only first value of array)
{
info : "stocks",
sales : "analytics"
}
//obj2
{
city : "SG"
}
I think you have overcomplicated this. Look at the example below. The logic goes like this:
Iterate over details keys
If a value under the key is an array, then create the key in the map and assign the value[0]
If a value under the key is not an array, then simply copy its value into the map
And that's enough to achieve what you want.
function newObj(obj){
let map = {};
obj.forEach(e => {
let details = e.details;
Object.keys(details).forEach(key => {
var value = details[key];
if (Array.isArray(value) && value.length > 0){
map[key] = value[0];
} else {
map[key] = value;
}
});
});
return map;
}
var obj1 = [
{
details: {
"info":["stocks","finance",""],
"sales":["analytics"]
}
}
];
var obj2 = [
{
details: {
"city":"SG"
}
}
];
var r1 = newObj(obj1);
var r2 = newObj(obj2);
console.log(r1);
console.log(r2);
Here's a very concise solution thanks to destructuring assignments:
function newObj(obj) {
const [{ details }] = obj;
const entries = Object.entries(details)
.map(([key, value]) => ([key, Array.isArray(value) ? value[0] : value]));
return Object.fromEntries(entries);
}
Live example:
'use strict';
function newObj(obj) {
const [{ details }] = obj;
const entries = Object.entries(details)
.map(([key, value]) => ([key, Array.isArray(value) ? value[0] : value]));
return Object.fromEntries(entries);
}
const obj1 = [
{
details: {
info: ['stocks', 'finance', ''],
sales: ['analytics']
}
}
];
const obj2 = [
{
details: {
city: 'SG'
}
}
];
console.log(newObj(obj1));
console.log(newObj(obj2));

Javascript unflatten array/change datastructure

So heres the problem and heres the fiddle: https://jsfiddle.net/6zqco0mj/
const start = [{'a':'b'}, {'b':'c'}, {'c':'d'}, {'d':'e'}]
end =
{a:
{b:
{c:
{
d: {}
}
}
}
}
I have some code but not sure how would I dig deeper into an object
const start = [{'b':'c'}, {'a':'b'}, {'c':'d'}, {'d':'e'}];
const end = {};
function convert(key) {
const obj = getObj(key);
if(obj) {
const temp = {};
temp[obj[key]] = convert(obj[key]);
//findKey(obj[key]);
end[key] = temp;
}
}
function getObj(key) {
const foo = start.find((el, i) => { if(el[key]) { return el[key] } });
return foo;
}
function findKey(k) {
// what goes here?
}
convert('a');
console.log(end);
i think you went in the other way around for your aproach of recursivity; i gave it a try and this is what i got so far
const start = [{'b':'c'}, {'a':'b'}, {'c':'d'}, {'d':'e'}];
function convert(key, object) {
const obj = getObj(key);
if(obj) {
object[obj[key]] = {};
convert(obj[key], object[obj[key]]);
}
}
function getObj(key) {
const foo = start.find((el, i) => { if(el[key]) { return el[key] }});
return foo;
}
const end = { a: {}};
convert('a', end.a);
console.log(end);
You could use an object structure for collecting the data and build the tree.
This solutiotion works with unsorted data.
For getting the root properties, all keys and values are collected and only the subset is taken.
var data = [{ d: 'e' }, { b: 'c' }, { c: 'd' }, { a: 'b' }, { b : 'z' }],
tree = function (data) {
var keys = new Set,
values = new Set,
r = Object.create(null);
data.forEach(function (o) {
var [key, value] = Object.entries(o)[0];
keys.add(key);
values.add(value);
r[value] = r[value] || {};
r[key] = r[key] || {};
r[key][value] = r[key][value] || r[value];
});
values.forEach(v => keys.delete(v));
return Object.assign(...Array.from(keys, k => ({ [k]: r[k] })));
}(data);
console.log(tree);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Recursively find keys on an object

I have a javascript object structured like this;
brand: {
group: {
subGroup: {
items: []
},
otherSub: {
items: []
}
}
}
Given an array of keys ['brand', 'group', 'newGroup', 'newSubGroup'] I want to split the keys into found and missing keys. So for the structure above I should get back;
present = ['brand', 'group']
missing = ['newGroup', 'newSubGroup']
I'm using ES6 and have lodash available, but struggling to find a clean way to produce this.
This is not to just check existence, it's recursively find the keys and return those present and the remaining ones.
Here's a pretty sketchy way that works.
const find = (keys, obj) => {
const string = JSON.stringify(obj);
return keys.reduce(({ present, missing }, key) => {
const match = string.match(new RegExp(`"${key}":`));
if (match) {
present.push(key);
} else {
missing.push(key);
}
return { present, missing };
}, { present: [], missing: [] });
}
You can use this function made for you ;)
var getAttrs = function(obj) {
return [].concat.apply([], Object.keys(obj).map(function (key) {
var results = [key]
if (typeof obj[key] === 'object') {
Array.prototype.push.apply(results, getAttrs(obj[key]))
}
return results
}))
}
It return the list of properties and children properties.
getAttrs({brand: {
group: {
subGroup: {
items: []
},
otherSub: {
items: []
}
}
}})
> ["brand", "group", "subGroup", "items", "otherSub", "items"]
And you can use it like so:
var lookingFor = ['brand', 'group', 'newGroup', 'newSubGroup']
var existings = getAttrs(obj)
var missings = []
var presents = []
lookingFor.forEach(attr => {
if (existings.indexOf(attr) === -1) {
missings.push(attr)
} else {
presents.push(attr)
}
})
I wrote a function to recursively get unique keys from a nested object, then filtered the array of all the keys you mentioned checking which were present in the result of my function.
var thisObject = {
brand: {
group: {
subGroup: {
items: []
},
otherSub: {
items: []
}
}
}
};
var arr_full = ['brand', 'group', 'newGroup', 'newSubGroup'] ;
var key_array = [];
function addToKeyArray( key_array, object ){
for( var key in object ){
// only get unique keys
if( key_array.indexOf( key ) === -1 ){
key_array.push( key );
}
// concat the result of calling this function recurrsively on object[key]
key_array.concat( addToKeyArray( key_array, object[key] ) );
}
return key_array;
}
var test = addToKeyArray( [], thisObject );
var missing = arr_full.filter( function( el ) {
return test.indexOf( el ) < 0;
});
console.log( test );
console.log( missing )
You can create recursive function using for...in loop inside another function and return object as result..
var obj = {"brand":{"group":{"subGroup":{"items":[]},"otherSub":{"items":[]}}}}
var keys = ['brand', 'group', 'newGroup', 'newSubGroup'] ;
function findKeys(data, keys) {
keys = keys.slice();
function findPresent(data, keys) {
var result = []
for(var i in data) {
if(typeof data[i] == 'object') result.push(...findPresent(data[i], keys))
var index = keys.indexOf(i);
if(index != -1) result.push(...keys.splice(index, 1))
}
return result
}
return {present: findPresent(data, keys), missing: keys}
}
console.log(findKeys(obj, keys))
To keep things clean and readable you can use "for in", inside a nested function for your recursion.
function recur(obj) {
let preMiss = {
present: [],
missing: []
}
let root = traverse => {
for (let key in traverse) {
if (Array.isArray(traverse[key].items)) {
preMiss.missing.push(key);
}
if (typeof traverse[key] === 'object' && !Array.isArray(traverse[key].items)) {
preMiss.present.push(key);
root(traverse[key])
}
}
}
root(obj);
return preMiss;
}
const object = {
brand: {
group: {
subGroup: {
items: []
},
otherSub: {
items: []
}
}
}
}
console.log(Object.entries(recur(object)));
var toFind = ['brand', 'group', 'newGroup', 'newSubGroup'],
found = [];
var o = {
brand: {
group: {
subGroup: {
items: []
},
otherSub: {
items: []
}
}
}
}
//called with every property and its value
function process(key,value) {
var i = toFind.indexOf(key);
if(i !== -1){
found.push(key);
toFind.splice(i, 1);
}
}
function traverse(o,func) {
if(!toFind.length) return;
for (var i in o) {
func.apply(this,[i,o[i]]);
if (o[i] !== null && typeof(o[i])=="object") {
//going one step down in the object tree!!
traverse(o[i],func);
}
}
}
traverse(o,process);
console.log(found); // present
console.log(toFind); // absent
Traverse method taken from https://stackoverflow.com/a/722732/1335165
Even though this question is a bit older, I want to present a rather short solution to the problem.
const recursivelyGetKeys = obj => Object.keys(obj).map(key => typeof obj[key] === 'object'
? [...recursivelyGetKeys(obj[key]), key] : [key]).reduce((p, c) => [...p, ...c], [])
This function will return all keys in the object, so a call to the array arr with
const arr = {
brand: {
group: {
subGroup: {
items: []
},
otherSub: {
items: []
}
}
}
}
will output:
const keys = recursivelyGetKeys(arr) // = ["items", "subGroup", "items", "otherSub", "group", "brand"]
Now to find the intersection set of this and find = ['brand', 'group', 'newGroup', 'newSubGroup'], do:
const found = keys.filter(key => find.some(val === key))
const missing = keys.filter(key => find.every(val !== key))

Convert returned JSON Object Properties to (lower first) camelCase

I have JSON returned from an API like so:
Contacts: [{ GivenName: "Matt", FamilyName: "Berry" }]
To keep this consistent with my code style (camelCase - lower case first letter) I want to transform the array to produce the following:
contacts: [{ givenName: "Matt", familyName: "Berry" }]
What's the easiest/best way to do this? Create a new Contact object and iterate over all the contacts in the returned array?
var jsonContacts = json["Contacts"],
contacts= [];
_.each(jsonContacts , function(item){
var contact = new Contact( item.GivenName, item.FamilyName );
contacts.push(contact);
});
or can I map the original array or transform it somehow?
If you would use lodash instead of underscore, this would do:
_.mapKeys(obj, (v, k) => _.camelCase(k))
This would convert both TitleCase and snake_case to camelCase. Note that it is not recursive though.
Here's a reliable, recursive function that will properly camelCase all of a JavaScript object's properties:
function toCamel(o) {
var newO, origKey, newKey, value
if (o instanceof Array) {
return o.map(function(value) {
if (typeof value === "object") {
value = toCamel(value)
}
return value
})
} else {
newO = {}
for (origKey in o) {
if (o.hasOwnProperty(origKey)) {
newKey = (origKey.charAt(0).toLowerCase() + origKey.slice(1) || origKey).toString()
value = o[origKey]
if (value instanceof Array || (value !== null && value.constructor === Object)) {
value = toCamel(value)
}
newO[newKey] = value
}
}
}
return newO
}
Test:
var obj = {
'FirstName': 'John',
'LastName': 'Smith',
'BirthDate': new Date(),
'ArrayTest': ['one', 'TWO', 3],
'ThisKey': {
'This-Sub-Key': 42
}
}
console.log(JSON.stringify(toCamel(obj)))
Output:
{
"firstName":"John",
"lastName":"Smith",
"birthDate":"2017-02-13T19:02:09.708Z",
"arrayTest": [
"one",
"TWO",
3
],
"thisKey":{
"this-Sub-Key":42
}
}
You can do this with this recursive function (with lodash and ES6):
import { camelCase } from 'lodash';
const camelizeKeys = (obj) => {
if (Array.isArray(obj)) {
return obj.map(v => camelizeKeys(v));
} else if (obj != null && obj.constructor === Object) {
return Object.keys(obj).reduce(
(result, key) => ({
...result,
[camelCase(key)]: camelizeKeys(obj[key]),
}),
{},
);
}
return obj;
};
Test:
const obj = {
'FirstName': 'John',
'LastName': 'Smith',
'BirthDate': new Date(),
'ArrayTest': ['one', 'TWO', 3],
'ThisKey': {
'This-Sub-Key': 42
}
}
console.log(JSON.stringify(camelizeKeys(obj)))
Output:
{
"firstName": "John",
"lastName": "Smith",
"birthDate": "2018-05-31T09:03:57.844Z",
"arrayTest":[
"one",
"TWO",
3
],
"thisKey":{
"thisSubKey": 42
}
}
To change a plain object's keys from snake_case to camelCase recursively try the following
(which uses Lodash):
function objectKeysToCamelCase(snake_case_object) {
var camelCaseObject = {};
_.forEach(
snake_case_object,
function(value, key) {
if (_.isPlainObject(value) || _.isArray(value)) { // checks that a value is a plain object or an array - for recursive key conversion
value = objectKeysToCamelCase(value); // recursively update keys of any values that are also objects
}
camelCaseObject[_.camelCase(key)] = value;
}
)
return camelCaseObject;
};
test in this PLUNKER
Note: also works recursively for objects within arrays
Using lodash and ES6, this will replace all keys recursively to camelcase:
const camelCaseKeys = (obj) => {
if (!_.isObject(obj)) {
return obj;
} else if (_.isArray(obj)) {
return obj.map((v) => camelCaseKeys(v));
}
return _.reduce(obj, (r, v, k) => {
return {
...r,
[_.camelCase(k)]: camelCaseKeys(v)
};
}, {});
};
Just use humps
humps.camelize('hello_world');
humps.camelizeKeys(object, options); // will work through entire object
https://www.npmjs.com/package/humps
This is a great use case for axios interceptors
Basically, define a client class and attach a before/after interceptor that converts the request/response data.
export default class Client {
get(url, data, successCB, catchCB) {
return this._perform('get', url, data, successCB, catchCB);
}
post(url, data, successCB, catchCB) {
return this._perform('post', url, data, successCB, catchCB);
}
_perform(method, url, data, successCB, catchCB) {
// https://github.com/axios/axios#interceptors
// Add a response interceptor
axios.interceptors.response.use((response) => {
response.data = toCamelCase(response.data);
return response;
}, (error) => {
error.data = toCamelCase(error.data);
return Promise.reject(error);
});
// Add a request interceptor
axios.interceptors.request.use((config) => {
config.data = toSnakeCase(config.data);
return config;
}, (error) => {
return Promise.reject(error);
});
return axios({
method: method,
url: API_URL + url,
data: data,
headers: {
'Content-Type': 'application/json',
},
}).then(successCB).catch(catchCB)
}
}
Here's a gist with a longer example using React/axios.
there's a nice npm module for this..
https://www.npmjs.com/package/camelcase-keys
npm install camelcase-keys
const camelcaseKeys = require( "camelcase-keys" );
camelcaseKeys( { Contacts: [ { GivenName: "Matt", FamilyName: "Berry" } ] }, { deep: true } );
will return...
{ contacts: [ { givenName: "Matt", familyName: "Berry" } ] }
This solution based on the plain js solution above, uses loadash and Keeps an array if passed as a parameter and Only change the Keys
function camelCaseObject(o) {
let newO, origKey, value
if (o instanceof Array) {
newO = []
for (origKey in o) {
value = o[origKey]
if (typeof value === 'object') {
value = camelCaseObject(value)
}
newO.push(value)
}
} else {
newO = {}
for (origKey in o) {
if (o.hasOwnProperty(origKey)) {
newO[_.camelCase(origKey)] = o[origKey]
}
}
}
return newO
}
// Example
const obj = [
{'my_key': 'value'},
{'Another_Key':'anotherValue'},
{'array_key':
[{'me_too':2}]
}
]
console.log(camelCaseObject(obj))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
Using lodash, you can do it like this:
export const toCamelCase = obj => {
return _.reduce(obj, (result, value, key) => {
const finalValue = _.isPlainObject(value) || _.isArray(value) ? toCamelCase(value) : value;
return { ...result, [_.camelCase(key)]: finalValue };
}, {});
};
Well I took up the challenge and think I figured it out:
var firstToLower = function(str) {
return str.charAt(0).toLowerCase() + str.slice(1);
};
var firstToUpper = function(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
};
var mapToJsObject = function(o) {
var r = {};
$.map(o, function(item, index) {
r[firstToLower(index)] = o[index];
});
return r;
};
var mapFromJsObject = function(o) {
var r = {};
$.map(o, function(item, index) {
r[firstToUpper(index)] = o[index];
});
return r;
};
// Map to
var contacts = [
{
GivenName: "Matt",
FamilyName: "Berry"
},
{
GivenName: "Josh",
FamilyName: "Berry"
},
{
GivenName: "Thomas",
FamilyName: "Berry"
}
];
var mappedContacts = [];
$.map(contacts, function(item) {
var m = mapToJsObject(item);
mappedContacts.push(m);
});
alert(mappedContacts[0].givenName);
// Map from
var unmappedContacts = [];
$.map(mappedContacts, function(item) {
var m = mapFromJsObject(item);
unmappedContacts.push(m);
});
alert(unmappedContacts[0].GivenName);
Property converter (jsfiddle)
The trick is handling the objects as arrays of object properties.
Here's handy library you might wanna try:
https://www.npmjs.com/package/camelize2
You simply need to install it with npm install --save camelize2 and then
const camelize = require('camelize2')
const response = {
Contacts: [{ GivenName: "Matt", FamilyName:"Berry" }]
}
const camelizedResponse = camelize(response)
Solution similar to #brandonscript, but in more ES6-functional way:
const camelCaseString = str => (
(str.charAt(0).toLowerCase() + str.slice(1) || str).toString()
);
const objectToCamelCase = val => {
if (typeof val != 'object' || val === null) {
return val;
}
if (val instanceof Array) {
return val.map(objectToCamelCase);
}
return Object.keys(val)
.filter(prop => val.hasOwnProperty(prop))
.map(prop => ({[camelCaseString(prop)]: objectToCamelCase(val[prop])}))
.reduce((prev, current) => ({...prev, ...current}))
};
// Example:
let converted = objectToCamelCase({UserId: 1, Hobbies: [{Id: 1, Label: "Read"}], Name: "John Doe"});
console.log(converted)
I needed a generic method that accepted an array or object. This is what I'm using (I borrowed KyorCode's firstToLower() implementation):
function convertKeysToCamelCase(obj) {
if (!obj || typeof obj !== "object") return null;
if (obj instanceof Array) {
return $.map(obj, function(value) {
return convertKeysToCamelCase(value);
});
}
var newObj = {};
$.each(obj, function(key, value) {
key = key.charAt(0).toLowerCase() + key.slice(1);
if (typeof value == "object" && !(value instanceof Array)) {
value = convertKeysToCamelCase(value);
}
newObj[key] = value;
});
return newObj;
};
Example calls:
var contact = { GivenName: "Matt", FamilyName:"Berry" };
console.log(convertKeysToCamelCase(contact));
// logs: Object { givenName="Matt", familyName="Berry"}
console.log(convertKeysToCamelCase([contact]));
// logs: [Object { givenName="Matt", familyName="Berry"}]
console.log(convertKeysToCamelCase("string"));
// logs: null
console.log(contact);
// logs: Object { GivenName="Matt", FamilyName="Berry"}
Took the challenge with lodash and some es6+ features
Here is my implementation with the reduce function.
function deeplyToCamelCase(obj) {
return _.reduce(obj, (camelCaseObj, value, key) => {
const convertedDeepValue = _.isPlainObject(value) || _.isArray(value)
? deeplyToCamelCase(value)
: value;
return { ...camelCaseObj, [_.camelCase(key)] : convertedDeepValue };
}, {});
};
Use lodash ...
function isPrimitive (variable) {
return Object(variable) !== variable
}
function toCamel (variable) {
if (isPrimitive(variable)) {
return variable
}
if (_.isArray(variable)) {
return variable.map(el => toCamel(el))
}
const newObj = {}
_.forOwn(variable, (value, key) => newObj[_.camelCase(key)] = toCamel(value))
return newObj
}
This function loop recursively through the object keys and using lodash returns a new object with every field converted to camelCase. It works also with arrays, nested arrays, nested objects.
function deepCamelCase (obj) {
const c = {}
if (typeof obj !== 'object') return obj
_.mapKeys(obj, (v, k) => {
let w = {}
if (typeof v === 'object') {
if (Array.isArray(v)) {
const k = []
for (const i of v) {
k.push(deepCamelCase(i))
}
} else {
_.mapValues(v, (n, m) => {
if (Array.isArray(n)) {
const k = []
for (const i of n) {
k.push(deepCamelCase(i))
}
w[_.camelCase(m)] = k
} else {
w[_.camelCase(m)] = deepCamelCase(n)
}
})
}
} else {
w = v
}
c[_.camelCase(k)] = w
})
return c
}
Updated code using the reference from https://plnkr.co/edit/jtsRo9yU12geH7fkQ0WL?p=preview
This handles the Objects with array with objects inside it too and so on, by keeping arrays as arrays (which you can iterate over using map)
function snakeToCamelCase(snake_case_object){
var camelCaseObject;
if (isPlainObject(snake_case_object)) {
camelCaseObject = {};
}else if(isArray(snake_case_object)){
camelCaseObject = [];
}
forEach(
snake_case_object,
function(value, key) {
if (isPlainObject(value) || isArray(value)) {
value = snakeToCamelCase(value);
}
if (isPlainObject(camelCaseObject)) {
camelCaseObject[camelCase(key)] = value;
}else if(isArray(camelCaseObject)){
camelCaseObject.push(value);
}
}
)
return camelCaseObject;
}
This is my take; more readable and with less nesting than brandoncode's implementation, and with more room for handling edge cases like Date (which isn't handled, by the way) or null:
function convertPropertiesToCamelCase(instance) {
if (instance instanceof Array) {
var result = [];
for (var i = 0; i < instance.length; i++) {
result[i] = convertPropertiesToCamelCase(instance[i]);
}
return result;
}
if (typeof instance != 'object') {
return instance;
}
var result = {};
for (var key in instance) {
if (!instance.hasOwnProperty(key)) {
continue;
}
result[key.charAt(0).toLowerCase() + key.substring(1)] = convertPropertiesToCamelCase(instance[key]);
}
return result;
}
Building on goredwards answer (which didn't handle the array fields correctly)
function objectKeysToCamelCase(snake_case_object) {
let camelCaseObject = {}
_.forEach(
snake_case_object,
function(value, key) {
if (_.isPlainObject(value)) {
value = objectKeysToCamelCase(value)
} else if (_.isArray(value)) {
value = value.map(v => _.isPlainObject(v) ? objectKeysToCamelCase(v) : v)
}
camelCaseObject[_.camelCase(key)] = value
},
)
return camelCaseObject
}
here is code I found for it, not fully tested though, but worth sharing.
It is far more readable than other answers, not sure about performance.
test it http://jsfiddle.net/ms734bqn/1/
const toCamel = (s) => {
return s.replace(/([-_][a-z])/ig, ($1) => {
return $1.toUpperCase()
.replace('-', '')
.replace('_', '');
});
};
const isArray = function (a) {
return Array.isArray(a);
};
const isObject = function (o) {
return o === Object(o) && !isArray(o) && typeof o !== 'function';
};
const keysToCamel = function (o) {
if (isObject(o)) {
const n = {};
Object.keys(o)
.forEach((k) => {
n[toCamel(k)] = keysToCamel(o[k]);
});
return n;
} else if (isArray(o)) {
return o.map((i) => {
return keysToCamel(i);
});
}
return o;
};
Pure JavaScript, shoud work fine
function convertKeysToCamelCase(object) {
if(object === undefined || object === null || typeof object !== "object") {
return object;
} else {
if(Array.isArray(object)) {
return object.map(item => convertKeysToCamelCase(item));
} else {
return Object.entries(object).reduce((result, [key, value]) => {
result[key.charAt(0).toLowerCase() + key.slice(1)] = convertKeysToCamelCase(value);
return result;
}, {});
}
}
}
you can do this simply by using json-case-convertor
const jcc = require('json-case-convertor')
const jsonData = ''//you json data to convert
const camelCasedJson = jcc.camelCaseKeys(jsonData) //Convert all the keys of object to snake case
This will handle all cascaded object as well
Convert object keys to camelCase with deep.
import _ from 'lodash';
export function objectKeysToCamelCase(entity) {
if (!_.isObject(entity)) return entity;
let result;
result = _.mapKeys(entity, (value, key) => _.camelCase(key));
result = _.mapValues(result, (value) => objectKeysToCamelCase(value));
return result;
}

Categories