Garavani Garavani - 6 months ago 19
Javascript Question

How can I get value of first key/value pair in forEach loop?

I have the following forEach loop to iterate over stored jQuery selectors:

contentExtras = [
{ right: $right_mask, start: aVariable, end: 0 },
{ right: $le, start: 0, end: bVariable },
{ left: $left_mask, start: cVariable, end: 0 }
];


Now I can do:

contentExtras.forEach( function( item ) {
item.right.css( { top: item.start } );
} );


or:

contentExtras.forEach( function( item ) {
item.left.css( { bottom: item.start } );
} );


Now I am looking for a way to do get the value of every first key/value pair independent of wether it is "right" or "left".

In the way that I could do something like:

contentExtras.forEach( function( item ) {
item.["both left and right"].css( { bottom: item.start } );
} );


I tried things like: item.[0] but without success.
Does this explain sufficiently what I need? Thanks in advance for help!

Answer

Use Object.keys()

Or just ||(Logical OR) operators

contentExtras = [{
  right: '$right_mask',
  start: '-rightX',
  end: 0
}, {
  right: '$le',
  start: 0,
  end: '-leX'
}, {
  left: '$left_mask',
  start: '-rightX',
  end: 0
}];

contentExtras.forEach(function(item) {
  var key = Object.keys(item)[0]; //Get the first key
  console.log(item[key])
    //OR
  console.log(item.left || item.right);
});