-6

I have two JSON objects, and I want to append newData into existingData.

existingData = {"School Name" : "Albert"}
newData = {"Teacher Name" : "Ms. Mithcell"}

This is the output I want:

existingData = {"School Name" : "Albert" , "Teacher Name" : "Ms. Mithcell"};

How can I do this?

Nicholas Smith
  • 574
  • 1
  • 14
  • 25
casillas
  • 15,701
  • 19
  • 102
  • 197

3 Answers3

1

Javascript has the Object.assign function.

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

existingData = {"School Name" : "Albert"}
newData = {"Teacher Name" : "Ms. Mithcell"}

Object.assign(existingData, newData) 

console.log(existingData); // {School Name: "Albert", Teacher Name: "Ms. Mithcell"}

Object.assign( originalObject, newObject ) will return originalObject with newObject merged into it.

Magnum
  • 2,061
  • 3
  • 14
  • 21
1

For javascript its object not python like dictionary :P, Just use Spread Syntax to get your job done.

existingData = {"School Name" : "Albert"}
newData = {"Teacher Name" : "Ms. Mithcell"}
result = {...existingData, ...newData};
console.log(result);
Always Sunny
  • 32,751
  • 7
  • 52
  • 86
1

You can do it this way for a more orthodox approach:

existingData = {"School Name" : "Albert"};
newData = {"Teacher Name" : "Ms. Mithcell"};

var new_keys = Object.keys(newData);

for (var i = 0; i < new_keys.length; i++){
  existingData[new_keys] = newData[new_keys[i]];
}

console.log(existingData);
Nicholas Smith
  • 574
  • 1
  • 14
  • 25