0

lets say I have an object that looks like this.

{
    source : 1,
    target : 0
}

The object is generated on the fly as part of some data that drives a d3.js visualisation. The object indicates the link between 2 data sets in another object.

I have a filter in my visualisation that shows the data as if it were coming from a different source, so basically the link data needs to invert. Sources become targets and targets become sources so it would need to look like this,

{
    source : 0,
    target : 1
}

Is there a better way of doing then looping through my object and on each interation getting the source and target storing them in variables and then reassigning them?

Udders
  • 6,914
  • 24
  • 102
  • 194
  • 1
    You mean something like this, temp=a; a=b; b=temp; if so then this is the only way you can swap values – GraveyardQueen Nov 15 '16 at 08:59
  • http://stackoverflow.com/questions/23013573/swap-key-with-value-json look at this. – Dhaval Soni Nov 15 '16 at 09:11
  • d3 doesn't allow you to add an extra translate step where you could do this conversion? Any chance you could show more about how/where you are manipulating the data, and where you make the current transform/translations? – Icepickle Nov 15 '16 at 09:41

1 Answers1

0

You could get the keys and swap the values wit the help of a temp variable.

var object = { source: 1, target: 0 },
    temp,
    keys = Object.keys(object);

temp = object[keys[0]];
object[keys[0]] = object[keys[1]];
object[keys[1]] = temp;

console.log(object);

ES6 with destructuring

var object = { source: 1, target: 0 },
    keys = Object.keys(object);

[object[keys[0]], object[keys[1]]] = [object[keys[1]], object[keys[0]]];

console.log(object);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392