Get all the fields in the object that gave the word and convert all the values of these fields
I have object
. eg,
{
startDate: 2141242141,
adress: '',
endDate: 2141242141,
billings: {
startBillingDate: 2142421421421,
endBillingDate: 2142421421421
}
amount: 100
}
I need to get all fields that contain the word "Date" (or "date") and convert them all to string date format.
Who can help.
source to share
You can accomplish these properties with Object.keys()
.
And for each, property
check if its value is not object
and contains a string date
using k.match(/date/i)
to change it to value date
. Otherwise, if the object does the same with its properties in a recursive way.
This is what you need:
function transformProperties(obj) {
Object.keys(obj).forEach(function(k) {
if ((typeof obj[k]) !== "object" && k.match(/date/i)) {
obj[k] = new Date(obj[k]);
} else if ((typeof obj[k]) == "object") {
let sub = obj[k];
transformProperties(sub);
}
});
}
Demo:
var o = {
startDate: 2141242141,
adress: '',
endDate: 2141242141,
billings: {
startBillingDate: 2142421421421,
endBillingDate: 2142421421421
},
amount: 100
};
function transformProperties(obj) {
Object.keys(obj).forEach(function(k) {
if ((typeof obj[k]) !== "object" && k.match(/date/i)) {
obj[k] = new Date(obj[k]);
} else if ((typeof obj[k]) == "object") {
let sub = obj[k];
transformProperties(sub);
}
});
}
transformProperties(o);
console.log(o);
source to share
This recursive function should convert all dates to ISO strings:
obj = convertDatesToString(obj);
function convertDatesToString(obj) {
Object.keys(obj).forEach((key) => {
if(key.toLowerCase().match(/date/)){
obj[key] = new Date(obj[key]).toISOString();
} else if (obj[key] instanceof Object) {
obj[key] = convertDatesToString(obj[key]);
}
});
return obj;
}
obj = {
startDate: 2141242141,
adress: '',
endDate: 2141242141,
billings: {
startBillingDate: 2142421421421,
endBillingDate: 2142421421421
},
amount: 100
};
obj = convertDatesToString(obj);
console.log(obj);
function convertDatesToString(obj) {
Object.keys(obj).forEach((key) => {
if(key.toLowerCase().match(/date/)){
obj[key] = new Date(obj[key]).toISOString();
} else if (obj[key] instanceof Object) {
obj[key] = convertDatesToString(obj[key]);
}
});
return obj;
}
source to share
I would create a function to recursively iterate over the properties of an object, and later I would call the whole function to create integer transformations:
function forEachProperty(obj, actionFn) {
Object.keys(obj).forEach(
property => {
actionFn(obj, property);
if (typeof obj[property] == "object") {
forEachProperty(obj[property], actionFn);
}
}
);
}
var obj = {
startDate: 2141242141,
adress: '',
endDate: 2141242141,
billings: {
startBillingDate: 2142421421421,
endBillingDate: 2142421421421
},
amount: 100
};
forEachProperty(obj, (obj, property) => {
if (property.toLowerCase().includes("date")) {
obj[property] = new Date(obj[property]);
}
});
console.log(JSON.stringify(obj));
source to share