【问题标题】:Jquery associate two arrays (key, value) into one arrayjQuery 将两个数组(键、值)关联到一个数组中
【发布时间】:2014-05-28 09:51:08
【问题描述】:

如何将两个包含键和值的数组与键-值对关联到一个数组中?

在 Mootools 中有 associate 功能:

var animals = ['Cow', 'Pig', 'Dog', 'Cat'];
var sounds = ['Moo', 'Oink', 'Woof', 'Miao'];
sounds.associate(animals);
// returns {'Cow': 'Moo', 'Pig': 'Oink', 'Dog': 'Woof', 'Cat': 'Miao'}

JQuery 中是否有任何类似的函数可以从这两个数组中获得相同的结果?

如果没有,我该怎么办?

【问题讨论】:

  • MooTools 比 jQuery 拥有更多的非 DOM 方法。您可以使用 MooTools 代替 jQuery...然后您拥有 MooTools 中的所有 DOM 方法,以及像 .associate() 方法这样的额外糖。

标签: javascript jquery arrays associations mootools


【解决方案1】:

JavaScript 并没有真正的关联数组,但您可以使用对象来代替。

Array.prototype.associate = function (keys) {
  var result = {};

  this.forEach(function (el, i) {
    result[keys[i]] = el;
  });

  return result;
};

var animals = ['Cow', 'Pig', 'Dog', 'Cat'];
var sounds = ['Moo', 'Oink', 'Woof', 'Miao'];
console.dir(sounds.associate(animals));

【讨论】:

  • 如果我在动物数组中有重复的值,并且我想将此值附加到以前的(比如说在数组中)值,它会返回一个数字而不是值。 var 动物 ​​= ['牛', '猪', '狗', '牛']; var sound = ['Moo', 'Oink', 'Woof', 'Miao'];
【解决方案2】:

您可以使用Array.prototype.reduce

var keys = ['a', 'b', 'c'],
    values = [1, 2, 3],
    associated = keys.reduce(function (previous, key, index) {
        previous[key] = values[index];
        return previous
    }, {})

console.log(associated) // Object {a: 1, b: 2, c: 3} 

reduce is not supported natively on IE<9 但您可以安全地使用Polyfill on the mdn site 您可以使用条件注释来定位,即仅​​

如果你想要一个可重用的函数是很简单的:

function associate(keys, values){
    return keys.reduce(function (previous, key, index) {
        previous[key] = values[index];
        return previous
    }, {})
} 

【讨论】:

    【解决方案3】:

    不是 jQuery,但很简单,可以用纯 JS 实现(这里是 fiddle):

    var animals = ['Cow', 'Pig', 'Dog', 'Cat'];
    var sounds = ['Moo', 'Oink', 'Woof', 'Miao'];
    var assoc = [];
    for(var i=0; i<animals.length; i++) {
        assoc[animals[i]] = sounds[i];
    }
    console.log(assoc);
    

    打印:

    Cat: "Miao"
    Cow: "Moo"
    Dog: "Woof"
    Pig: "Oink"
    

    【讨论】:

      【解决方案4】:

      你可以自己写类似这样的:

      Array.prototype.associate = function(arr){
          var index,
              output = Object.create(null);
      
          for(index = 0; index < this.length; index++){
              output[arr[index]] = this[index];
          }
      
          return output;
      };
      

      然后就可以按预期使用了,类似这样:

      var animals = ['Cow', 'Pig', 'Dog', 'Cat'];
      var sounds = ['Moo', 'Oink', 'Woof', 'Miao'];
      var x = sounds.associate(animals);
      

      x 中的结果是{'Cow': 'Moo', 'Pig': 'Oink', 'Dog': 'Woof', 'Cat': 'Miao'}


      DEMO - 复制 Mootool 的关联函数


      【讨论】:

        【解决方案5】:

        你可以在java scipt中使用。

        Array.prototype.associate= function(){
         var that = this;
         var associated ={};
         var len = that.length;
         for(var i=0; i < len; i++){
            associated[that[i]] = value[i];
         }
         return associated;
         } 
        var animals = ['Cow', 'Pig', 'Dog', 'Cat'];
        var sounds = ['Moo', 'Oink', 'Woof', 'Miao'];
        console.log(animals.associate(sounds));
        

        【讨论】:

          【解决方案6】:

          如果你可以在你的项目中添加一个像 lodash 这样的依赖,那么它就这么简单:

          let result = _.zip([key1, key2], [value1, value2])
          

          这将产生一个新的数组数组:

          [[key1, value1], [key2, value2]]
          

          对结果应用lodash函数fromPairs

          let finalResult = _.fromPairs(resultArrayFromPreviousCode)
          

          finalResult 现在是:

          { key1: value1, key2: value2 }
          

          希望有帮助!

          【讨论】:

            【解决方案7】:

            for...of 方法

            您还可以将for...of 语句与Array.prototype.entries() 结合使用,以使用一个数组作为键,另一个数组作为值来创建对象:

            const array_combine = (keys, values) => {
              const result = {};
              
              for (const [index, key] of keys.entries()) {
                result[key] = values[index];
              }
              
              return result;
            };
            
            const animals = ['Cow', 'Pig', 'Dog', 'Cat'];
            const sounds  = ['Moo', 'Oink', 'Woof', 'Miao'];
            
            console.log(array_combine(animals, sounds));

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2021-03-25
              • 2016-05-23
              • 2018-04-27
              • 1970-01-01
              • 1970-01-01
              • 2012-10-21
              • 2018-05-11
              • 2022-01-12
              相关资源
              最近更新 更多