Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
553 views
in Technique[技术] by (71.8m points)

javascript - Swap value of two properties on object(s)

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"};
object2 = {"key 2":"value 2"};

swapValuesInObject ("object1['key 1']","object2['key 2']",true)
// should result in:
// object1 === {"key 1":"value 2"};
// object2 === {"key 2":"value 1"};

Another example:

object1 = {"key 1":"value 1", "key 2":"value 2"};

swapValuesInObject ("object1['key 1']","object1['key 2']",1===1)
// should result in:
// object1 === {"key 1":"value 2", "key 2":"value 1"};

Here's what I've been able to come up with so far, but it's not much. Getting hung up on how to do the assignment.

function swapValuesInObject(property1, property2, condition) {
    if (condition) {
        // temp assignment
        var Obj1Value = property1;

        // do the switcheroo
        array1 = array2Value;
        array2 = array1Value;
    }
    return true;
};

What's the proper way to do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...