从Array填充jQuery对象

时间:2013-11-06 18:31:17

标签: jquery arrays

这是我的第一篇文章,在jQuery上相当新。我正在寻找一个优雅的解决方案来从数组

填充jQuery对象

我有一个动态数组“carsArray”。我喜欢将carsArray中的值填充到jquery对象中。我有点工作,但我发现它有两个问题。

  1. 我已经将carArray硬编码为只有5个值,这是不正确的。它应该是灵活的。
  2. 不优雅的编码。我知道有更好的方法来实现最终结果。
  3. ;jQuery(function($) {
    
        carsArray = ['Nissan','Toyota','BMW'] // this is dynamically build. It could have many more values.
    
        var carArray = new Array();
        $.each(carsArray, function ( key, value ) {
            carArray[key] = value;
        });
    
        // '101','102'.. are random indexes. It could be any distinct value.
    
        $.carspicker.designs['custom'] = {
            '101': [carArray[0]],
            '102': [carArray[1]],
            '103': [carArray[2]],
            '104': [carArray[3]],
            '105': [carArray[4]]
        };
    
    });
    

    真的很感激任何建议。谢谢!

2 个答案:

答案 0 :(得分:0)

jQuery(function($){

carsArray = ['Nissan','Toyota','BMW'] // this is dynamically build. It could have many more values.

var carObj= {}; //new object
$.each(carsArray, function ( key, value ) {
    carObj[key] = value;
});

// '101','102'.. are random indexes. It could be any distinct value.

$.carspicker.designs['custom'] = carObj;

}); OR

jQuery(function($){

carsArray = ['Nissan','Toyota','BMW'] // this is dynamically build. It could have many more values.

var carArray = new Array();
$.each(carsArray, function ( key, value ) {
    carArray[key] = value;
});

// '101','102'.. are random indexes. It could be any distinct value.

$.carspicker.designs['custom'] = carsObject(carArray);
function carsObject(arr) {
    var maxlength = arr.length,
        i,//this index in array as well as the unique key in the object
        carObj = {};
    for(i = 0; maxlength > i; i += 1) {
        carObj[i] = arr[i];
    }
    return carObj;
}

});

答案 1 :(得分:0)

据我所知,您希望将数组转换为对象,并且键是无关紧要的。你可以:

var cars = ['Nissan','Toyota','BMW'];

var obj = cars.reduce(function(memo, car){
    memo[car] = car;
    return memo;
}, {});

但它仅适用于EcmaScript 5。

使用jQuery,您可以使用extend函数。我不确定使用数组作为参数100%合法,但仍然是:

var obj = $.extend({}, cars);