1

So let's say I have four components, three children and one parent.

parentObject = {}
childOneObject = {starTime, endTime}
childTwoObject = {color, theme, junk}
childThreeObject = {starsInSky, wheelsOnCar, shoesOnFeet}

The parentObject should be made up of all these values to submit in the end.

At the end of the first component, a user will submit their data and it will get added to the parentObject. Which looks like this

parentObject = childOneObject

The user will continue on to step two and submit their info which works the same as step one, but if I write parentObject = childTwoObject

The original data is obviously destroyed. I'd like to know if there is a way to insert chunks of data into objects without destroying older data or having to target things line by line like

parentObject.startTime = 5:00

I do not like to have to do this because it's cumbersome to me.

4 Answers4

2

You can use spread operator. This operator will merge the child objects with parent object

const parentObject = {};
parentObject = { ...parentObject, ...childOneObject };
parentObject = { ...parentObject, ...childTwoObject };
parentObject = { ...parentObject, ...childThreeObject };

you can also do it in one step

const parentObject = {};
parentObject = { ...parentObject, ...childOneObj, ...childTwoObj, ...childThreeObj };
Yousaf
  • 27,861
  • 6
  • 44
  • 69
2

Just assign them all on-top-of the parent…

let parentObject = {}
let childOneObject = {startTime: 0, endTime: 1}
let childTwoObject = {color: 'red', theme: 'dark', junk: true}
let childThreeObject = {starsInSky: Number.MAX_VALUE, wheelsOnCar: 4, shoesOnFeet: 2}

Object.assign(parentObject, childOneObject, childTwoObject, childThreeObject)

console.log(parentObject)
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
1

It is very simple with the help of a spread operator.

// Inital  
parentObject = {}
//Step 1:
childOneObject = {starTime, endTime}
parentObject = {...childOneObject};
// Step 2
childTwoObject = {color, theme, junk}
parentObject = {...parentObject, ...childTwoObject}
// Step 3
childThreeObject = {starsInSky, wheelsOnCar, shoesOnFeet}
parentObject = {...parentObject, ...childThreeObject}
Siraj Alam
  • 9,217
  • 9
  • 53
  • 65
1

const parentObject = {}
const childOneObject = {starTime: 0, endTime: 1}
const childTwoObject = {color:'red', theme:'dark', junk:false}
const childThreeObject = {starsInSky:2, wheelsOnCar:4, shoesOnFeet:2}

const assignKeyVals = (parent, child) => {
   Object.entries(child).forEach(([key,val]) => parent[key] = val)
}

assignKeyVals(parentObject, childOneObject)
assignKeyVals(parentObject, childTwoObject)
assignKeyVals(parentObject, childThreeObject)

console.log(parentObject)
symlink
  • 11,984
  • 7
  • 29
  • 50