如何将包含键和值的两个数组关联到一个具有key->值对的数组?
在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中是否有类似的函数可以从这两个数组中获得相同的结果?
如果没有,我该怎么做?
答案 0 :(得分:5)
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));
答案 1 :(得分:2)
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 您可以使用条件注释来定位,即仅<9。
如果您想要一个可重用的功能,那么非常简单:
function associate(keys, values){
return keys.reduce(function (previous, key, index) {
previous[key] = values[index];
return previous
}, {})
}
答案 2 :(得分:1)
不是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"
答案 3 :(得分:1)
您可以自己编写类似的内容:
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的关联功能
答案 4 :(得分:1)
你可以在javascript中使用。
答案 5 :(得分:0)
如果您可以将 lodash 之类的依赖项添加到项目中,那么它就像以下一样简单:
let result = _.zip([key1, key2], [value1, value2])
这将生成一个新的数组数组:
[[key1, value1], [key2, value2]]
结果,从thePairs :
应用lodash函数let finalResult = _.fromPairs(resultArrayFromPreviousCode)
finalResult现在是:
{ key1: value1, key2: value2 }
希望有所帮助!
答案 6 :(得分:0)
您还可以结合使用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));