Sanchez9a
Sanchez9a

Reputation: 13

How to merge an object inside another object

I don't know if the question is right, but I want to do the following, I want the properties of "variable" to become part of the variable day.

The object being as follows: {seg: 60, min:1, dias: 7, semana: 1}

Remaining the object of the following way: Take into consideration that the object inside the object could be anyone and it does not have to be the property "variable" for what I would like to make it dynamic, reason why an arrangement like delete dia.variable and later to merge would not serve me.

With the code that I show you I have only obtained that the result is: {seg: 60, min:1, variable:{dias: 7, semana: 1}, dias: 7, semana: 1}

Any ideas on how I could do it more efficiently, and above all, do it.

const dia = {seg: 60, min:1, variable:{dias: 7, semana: 1}}
let varia = {}
let newDia = {}

const processJson = () => {
    Object.entries(dia).map(([name, value]) => {
        if(typeof(value) === 'object'){
            varia = value
            newDia = {...dia, ...variable}
        }
    })    
}

processJson()

Upvotes: 0

Views: 434

Answers (2)

AlexSp3
AlexSp3

Reputation: 2293

This is a universal method for flatting any object with 2 levels deep. It uses the array reduce method and the Object.keys() function:

const dia = { seg: 60, min: 1, variable: {dias: 7, semana: 1} }

function flatObject(o) {
  return Object.keys(o).reduce((result, key) => {
  
    // If there is a nested object, flat the object
    if (typeof o[key] === 'object' && ! Array.isArray(o[key]) && o[key] !== null) {
      for (const inKey in o[key]) {
        result[inKey] = o[key][inKey];
      }
    }
    // Just copy the value
    else {
      result[key] = o[key];
    }
    
    // Return accumulator
    return result;
  }, {});
}

console.log(flatObject(dia))

Upvotes: 1

Emiel Zuurbier
Emiel Zuurbier

Reputation: 20944

Start of by using a destructuring assignement to extract the seg, min and variable properties from the dia object.

const { seg, min, variable } = dia;

Then create a new object in which you set the seg and min properties with the destructured properties. For the variable property, use the spread syntax to place the properties of variable inside the same object.

const result = {
  seg,
  min,
  ...variable
};

const dia = {
  seg: 60,
  min: 1,
  variable: {
    dias: 7,
    semana: 1
  }
};

const { seg, min, variable } = dia;

const result = {
  seg,
  min,
  ...variable
};

console.log(result);

Upvotes: 1

Related Questions