How to create key value pair using two arrays in javascript?

安稳与你 提交于 2019-12-01 02:02:01

JavaScript is a very versatile language, so it is possible to do what you want in a number of ways. You could use a basic loop to iterate through the arrays, like this:

var keys=['en_US','es_ES', 'pt_PT','fr_FR','de_DE','ja_JP','it_IT']
var commonKeys=['en-*','es-*', 'pt-*','fr-*','de-*','ja-*','it-*', '*']

var i;
var currentKey;
var currentVal;

var result = {}


for (i = 0; i < keys.length; i++) {
    currentKey = commonKeys[i];
    currentVal = keys[i];
    result[currentKey] = currentVal;    
}

This example will work in all browsers.

You can use map() function on one array and create your objects

var keys=['en_US','es_ES', 'pt_PT','fr_FR','de_DE','ja_JP','it_IT'];
var commonKeys=['en-*','es-*', 'pt-*','fr-*','de-*','ja-*','it-*', '*'];

var output = keys.map(function(obj,index){
  var myobj = {};
  myobj[commonKeys[index]] = obj;
  return myobj;
});

console.log(output);

What you want to achieve is to create an object from two arrays. The first array contains the values and the second array contains the properties names of the object.

As in javascript you can create new properties with variales, e.g.

objectName[expression] = value; // x = "age"; person[x] = 18,

you can simply do this:

var keys=['en_US','es_ES', 'pt_PT','fr_FR','de_DE','ja_JP','it_IT'];
var commonKeys=['en-*','es-*', 'pt-*','fr-*','de-*','ja-*','it-*', '*'];

var langKeys = {};

var i;
for (i=0; i < keys.length; i++) {
    langKeys[commonKeys[i]] = keys[i];
}

EDIT

This will work only if both arrays have the same size (actually if keys is smaller or same size than commonKeys).

For the last element of langKeys in your example, you will have to add it manually after the loop.

What you wanted to achieve was maybe something more complicated, but then there is missing information in your question.

Try this may be it helps.

  var langKeys = {};
  var keys=['en_US','es_ES', 'pt_PT','fr_FR','de_DE','ja_JP','it_IT']
  var commonKeys=['en-*','es-*', 'pt-*','fr-*','de-*','ja-*','it-*', '*']
  function createArray(element, index, array) {
     langKeys[element]= keys[index];
     if(!keys[index]){
      langKeys[element]= keys[index-(commonKeys.length-1)];
     }
  }

  commonKeys.forEach(createArray);
  console.info(langKeys);

Use a for loop to iterate through both of the arrays, and assign one to the other using array[i] where i is a variable representing the index position of the value.

var keys = ['en_US', 'es_ES', 'pt_PT', 'fr_FR', 'de_DE', 'ja_JP', 'it_IT'];


var commonKeys = ['en-*', 'es-*', 'pt-*', 'fr-*', 'de-*', 'ja-*', 'it-*', '*'];

var langKeys = {};
for (var i = 0; i < keys.length; i++) {
  var commonkey = commonKeys[i];
  langKeys[commonkey] = keys[i];
}
console.log(JSON.stringify(langKeys));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!