简体   繁体   中英

Javascript array - merge two arrays into one

I have two arrays, one with name of the country and one with the currency type. I would like to merge these together and use the country key instead of the currencies array. What would be the best way to accomplish this?

This is what my code looks like now:

var country = new Array();
country["SEK"] = 'Sweden';
country["USD"] = 'United states';
var currencies = ["SEK","USD"];
var options = '';

for (var i = 0; i < currencies.length; i++) {
    options += '<option value="' + currencies[i] + '" id="' + currencies[i] + '">' + currencies[i] + ' (' + country[currencies[i]] + ')</option>';
}

It's a common misconception that you can just use this:

for (var currency in country) {
  result += { ... something done with both currency and country[currency] ... };
}

The catch here is that hash is technically unordered in JS, so you cannot guarantee the same order of these options.

The common alternative is using array of objects instead:

var countriesData = [
{
  country: 'Sweden',
  currency: 'SEK'
},
{
  country: 'United States',
  currency: 'USD'
}
];
for (var i = 0, l = countriesData.length; i < l; i++) {
  result += { something of countriesData[i].currency and countriesData[i].country };
}


As a sidenote, consider this...

 var country = new Array(); country["SEK"] = 'Sweden'; country["USD"] = 'United states'; console.log(country.length); // wait, what? 

... and 0 will be logged, not 2 - as probably expected. Again, there's no such thing as 'PHP-like associative array' in JS: there are objects and arrays (which are technically objects too; typeof country will give you 'object' string).

So this is what happens here: you create an Array object, and it inherits all the properties of Array.prototype (such as length ), in particular. Now you extend this Array with two properties - 'SEK' and 'USD'; but it's not the same as pushing these strings into array with push or some similar methods! That's why its length stays the same, introducing chaos and confusion. )

Try this:

var countries = {
    'Sweden': 'SEK',
    'United Stated': 'USD'
}, options = '', country;

for(country in countries) {
    options += '<option value="' + countries[country] + '" id="' + countries[country] + '">' + countries[country] + ' (' + country + ')</option>';
}

It seem uncomfortable to use arrays. Use json object json.org wikipedia instead, this way you can take advantage of the relation key-value. In addition you can also validate it with lint . No jQuery needed. So this is the code:

var currency = {
    "SEK": "Sweden",
    "USD": "United states",
    "GBP": "United Kingdom"
};

(function(obj) {
    var myselect = document.getElementById("currency");
    for (var key in obj) {
        var optElement = new Option( key+ " ( " + obj[key] + " ) ", key );
        optElement.id = key; //optElement.setAttribute ( "id", key);
        myselect.add ( optElement, null);
    }
})(currency);

​As for the function - I think it is better to do it with objects, instead of making a string and then adding it to the select. It is an anonymous function, so it is self-contained and won't interfere with any other code. Just use it after the select is created, or place it at the end of the page.

And jsfiddle example

Edit:

Using add() or innerHTML - in Chrome, innerHTML is not working. And it is better this way.

As for the removing of the options - there is remove() method. Use one of those:

var x = document.getElementById("currency");
for ( var i = x.length; i > 0; i-- ) { x.remove ( 0 ); }

or

while ( x.length > 0 )               { x.remove ( x.length - 1 ); }

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