javascript - How to swap several objects values? -
for example have 2 objects same keys:
var = { k1: "aa", k2: "ab", k3: "ac", k4: "ad", k5: "ae" } var b = { k1: "ba", k2: "bb", k3: "bc", k4: "bd", k5: "be" }
for example, need swap values k2, k3, k4 between these objects. so, want result:
a = { k1: "aa", k2: "bb", k3: "bc", k4: "bd", k5: "ae" } b = { k1: "ba", k2: "ab", k3: "ac", k4: "ad", k5: "be" }
is there way fast? believe can performed without adding intermediate object.
simple solution using object.keys()
, array.prototype.indexof()
functions:
var = {k1: "aa",k2: "ab",k3: "ac",k4: "ad",k5: "ae"}, b = {k1: "ba",k2: "bb",k3: "bc",k4: "bd",k5: "be"}, swapkeys = ['k2', 'k3', 'k4']; swapkeys.foreach(function (k) { if (k in && k in b) { var values = [a[k], b[k]]; a[k] = values[1]; b[k] = values[0]; } }); console.log(a); console.log(b);
Comments
Post a Comment