简体   繁体   English

如何在关联数组javascript中填充值

[英]How to populate values in associative array javascript

sorry for my bad english 对不起,我的英语不好

i am working in javascript and i have build an array i want to enter values in this array. 我在javascript中工作,我已经构建了一个数组,我想在这个数组中输入值。

var attribute_sets = [];
$('.attribute_set :selected').each(function(i, selected){
    attribute_sets[i]['id'] = $(selected).val(); // getting id 
    attribute_sets[i]['name'] = $(selected).text(); // getting name
});

Its giving me error 它给了我错误

TypeError: attribute_sets[i] is undefined TypeError:attribute_sets [i]未定义

also tried this one 也试过这个

attribute_sets[i]['id'].push($wk_jq(selected).val());

still getting same error 仍然得到同样的错误

can any one please guide me how can i insert values in this JS array. 任何人都可以指导我如何在这个JS数组中插入值。 i want output like this 我想要像这样的输出

array
    [0]
      'id':'1',
      'name':'abc'
    [1]
      'id':'2',
      'name':'xyz'

Use map() function. 使用map()函数。

attribute_sets = $('.attribute_set :selected').map(function(i, selected){
    return {
       'id' : $(this).val(),
       'name' : $(this).text(),
    }
}).get();

try 尝试

$('.attribute_set :selected').each(function(i, selected){
  attribute_sets.push({
   id: $(selected).val(), // getting id 
   name: $(selected).text() // getting name
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM