2016-04-21 11 views
-2

Ich habe 2 Hashes (Objekte) für ex.Merge Hash mit Eigenschaften Arrays

hash1 = {myKey: ["string1"]} 

hash2 = {myKey: ["string2"]} 

Ich möchte, dass sie zusammen verschmelzen, so dass am Ende ich etwas wie folgt erhalten würde -

{myKey: ["string1", "string2"] } 

ich $.extend versucht, aber das funktioniert nicht für Arrays als Eigenschaft

+3

Ihre Schlüssel nicht übereinstimmen. –

Antwort

1

Sie können nimm eine Funktion dafür.

function add(o, v) { 
 
    Object.keys(v).forEach(function (k) { 
 
     o[k] = o[k] || []; 
 
     v[k].forEach(function (a) { 
 
      o[k].push(a); 
 
     }); 
 
    }); 
 
} 
 

 

 
var hash1 = { myKey: ["string1"] }, 
 
    hash2 = { myKey: ["string2"] }; 
 

 
add(hash1, hash2); 
 
document.write('<pre>' + JSON.stringify(hash1, 0, 4) + '</pre>');

0

können Sie Array.prototype.push.apply() fusionieren Array

var hash1 = {myKey: ["string1"]}; 
 
var hash2 = {myKey: ["string1"]}; 
 
Array.prototype.push.apply(hash1.myKey, hash2.myKey) 
 
console.log(hash1)

0

Hinweis: Überprüfung der Groß- und Kleinschreibung Ihrer Schlüssel.

Sie können etwas tun:

hash1 = {myKey: ["string1"]} 
hash2 = {myKey: ["string2"]} 
var result = {}; 
for (var hash1Key in hash1) { 
    if (hash1.hasOwnProperty(hash1Key)) { 
     for (var hash2Key in hash2) { 
      if (hash2.hasOwnProperty(hash2Key)) { 
       if (hash1Key === hash2Key) { 
        result[hash1Key] = [hash1[hash1Key], hash2[hash2Key]] 
       } 
      } 
     } 
    } 
} 

anzeigen Live in jsFiddle