-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
  • 674
  • 1
  • 13
  • 27
casillas
  • 16,351
  • 19
  • 115
  • 215

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,299
  • 4
  • 17
  • 23
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);
A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103
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
  • 674
  • 1
  • 13
  • 27