0
  • Let's say you have 2 dynamic dictionaries.
  • Both dictionaries will always be the same length.
  • And both dictionaries will always share a matching "ID".
  • There are an unknown amount of entries in each dictionary. (e.g. both could have 4 entries, or both could have 20 entries)

for instance:

var dict1 = {};
var dict2 = {};

dict1.id = "3";
dict1.val1 = "4";

dict2.id = "3";
dict2.val2 = "6";

How can you merge both into 1 "final" dictionary, where they are merged at the id?

var main = {};
main.id = "3";
main.val1 = "4";
main.val2 = "6";
Penjimon
  • 469
  • 4
  • 20
  • This has nothing to do with jQuery, this is just normal JavaScript. The libraries that are used for dealing with data collections are underscore.js and and lodash. – Barmar Aug 07 '19 at 21:18
  • They're called objects in JavaScript, not dictionaries (that's Python). – Barmar Aug 07 '19 at 21:19
  • Look at the `Object.assign()` method. – Barmar Aug 07 '19 at 21:19
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign – Barmar Aug 07 '19 at 21:19
  • Duplicate: https://stackoverflow.com/questions/171251/how-can-i-merge-properties-of-two-javascript-objects-dynamically – Barmar Aug 07 '19 at 21:20
  • Actually, jQuery does have a method for this: `$.extend()`. The name is even in the title of your question, I'm surprised you didn't find it when you searched. – Barmar Aug 07 '19 at 21:21

1 Answers1

0

You can use jQuery.extend( target [, object1 ] [, objectN ] ):

Merge the contents of two or more objects together into the first object.

var dict1 = {};
var dict2 = {};

dict1.id = "3";
dict1.val1 = "4";

dict2.id = "3";
dict2.val2 = "6";

var main = $.extend(dict1, dict2);

console.log(main);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
gaetanoM
  • 41,594
  • 6
  • 42
  • 61