I have an array with keys and values which elements i want to push into 2 different arrays (key into one and value into another)
here is the code i have used:
// the array i want to split
var defaultc = {
'a':'r019',
'b':'r027',
'c':'r027',
'd':'r027',
'e':'r047'
};
// the array i want to add to
var step_layer = []; // keys to this
var step_colour = {}; // values to this
$('#reset').click(function() {
$.each(defaultc, function(layer, colour) {
// both these functions are working properly
apply_changes(layer, colour);
sumary(layer, colour);
});
// this part is not
for (var layer in defaultc) {
if (!defaultc.hasOwnProperty(layer)) {
step_layer.push(layer);
step_colour[layer].push(colour);
}}
return false;
});
You have an Object, not an Array. Its quite simple:
But as
.valuesis a non-standard method,.keysonly available on modern browsers and the iteration order of object properties is not fix, you should use a single loop over the object:And that’s where your code differs. First, you start with a
var step_colour = {};. This is a object again, to be used for a key-value-map. So, it even would be possible to access a property of it withstep_colour[layer], but this is stillundefined. You seem to assume that it would be an array, using.pushon it – that will throw an error (look into your debugging console). Im not sure what you want to achieve with that. Creating an array, cloning thedefaultcvariable?Another problem is
if (!defaultc.hasOwnProperty(layer)). First, yourdefaultcis a plain object and does not inherit any enumerable properties, so just leave that condition away. Second, as alllayers you loop over are own properties ofdefaultc, the block will never get executed.