Swap value of two properties on object(s)

后端 未结 2 1849
情话喂你
情话喂你 2020-12-19 08:11

I\'m trying to make a simple function that will swap the values of two properties on the same or different global objects.

object1 = {\"key 1\":\"value 1\"}         


        
相关标签:
2条回答
  • 2020-12-19 08:51

    I would do it as follows:

    var obj1 = {
        "key1" : "value1",
        "key2" : "Value2"
    };
    var obj2 = {
        "key3" : "value3",
        "key4" : "Value4"
    };
    
    function swap(sourceObj, sourceKey, targetObj, targetKey) {
        var temp = sourceObj[sourceKey];
        sourceObj[sourceKey] = targetObj[targetKey];
        targetObj[targetKey] = temp;
    }
    
    swap(obj1, "key1", obj1, "key2");
    swap(obj1, "key1", obj2, "key4");
    
    0 讨论(0)
  • 2020-12-19 09:10

    With ES6 destructuring, you can now swap without a temp variable. This applies to not only swapping variable values as in [a, b] = [b, a] but more complex expressions involving properties of objects, like so: [obj.key1, obj.key2] = [obj.key2, obj.key1]. To avoid more redundancy, you need to use a swap function:

    function swap(obj, key1, key2) {
       [obj[key1], obj[key2]] = [obj[key2], obj[key1]];
    }
    swap(obj, 'key1', 'key2');
    

    The same idea applies with two objects and two keys:

    function swap(obj1, key1, obj2, key2) {
       [obj1[key1], obj2[key2]] = [obj2[key2], obj1[key1]];
    }
    swap(obj1, 'key1', obj2, 'key2');
    
    0 讨论(0)
自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题