简体   繁体   中英

How to Push array values to diffrent arrays?

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;
});
var defaultc = {
    'a':'r019',
    'b':'r027',
    'c':'r027',
    'd':'r027',
    'e':'r047'
};

var step_layer = []; // keys to this
var step_colour = []; // values to this

for(var key in defaultc) {
   setip_layer.push(key);
   step_colour.push(defaultc[key]);
}

You have an Object, not an Array. Its quite simple:

var step_layer = Object.keys(defaultc); // array of property names
var step_colour = Object.values(defaultc); // arrray of property values

But as .values is a non-standard method, .keys only available on modern browsers and the iteration order of object properties is not fix, you should use a single loop over the object:

var step_layer = []; // array of property names
var step_colour = []; // arrray of property values
for (var layer in defaultc) {
    step_layer.push(layer);
    step_colour.push(defaultc[layer]);
}

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 with step_colour[layer] , but this is still undefined . You seem to assume that it would be an array, using .push on 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 the defaultc variable?

Another problem is if (!defaultc.hasOwnProperty(layer)) . First, your defaultc is a plain object and does not inherit any enumerable properties, so just leave that condition away. Second, as all layer s you loop over are own properties of defaultc , the block will never get executed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM