Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import * as _ from 'lodash';
- const requestBody = {
- a: {
- a2: 10,
- c: {
- h1: 5,
- },
- },
- b: 2,
- };
- const fetchedFromDatabase = {
- a: {
- a2: 100,
- g: {
- f1: 10,
- },
- c: {
- h1: 50,
- h2: 10,
- },
- },
- b: 10,
- };
- let currentValues = {};
- const updatedValues = {};
- const flattenUpdatedFieldsSeparatedByDot = flattenObject(requestBody);
- for (const separatedRequestField in flattenUpdatedFieldsSeparatedByDot) {
- const fetchedFromDatabaseValue = _.get(
- fetchedFromDatabase,
- separatedRequestField
- );
- currentValues = {
- ...currentValues,
- };
- _.set(currentValues, separatedRequestField.split('.'), fetchedFromDatabaseValue)
- }
- console.log(currentValues);
- // now _.merge()
- function flattenObject(value: any): Object {
- let toReturn: any = {};
- for (const i in value) {
- if (!value.hasOwnProperty(i)) {
- continue;
- }
- if (typeof value[i] == 'object') {
- const flatObject = flattenObject(value[i]);
- for (const x in flatObject) {
- if (!flatObject.hasOwnProperty(x)) continue;
- toReturn[i + '.' + x] = flatObject[x];
- }
- } else {
- toReturn[i] = value[i];
- }
- }
- return toReturn;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement