我正在创建一个 javascript 对象数组。在对象内部,我想要一个键,并且在同一个存储桶中包含与该键关联的所有属性。
例如食物[{水果: '苹果', '香蕉'}, {香料: '辣椒', '卡津'}]
如果键是唯一的,则添加到数组中,否则就放在同一个存储桶中。
下面的代码
$('.options li').each(function() {
$name = $(this).parent().attr('id');
$attr = $(this).attr('data-attr');
food[$name] = $attr;
});
最佳答案
<强> Working Fiddle
要实现此目的,您需要将每个关键字及其元素的数组存储起来。像这样的事情应该可以解决问题:
$('.options li').each(function() {
$name = $(this).parent().attr('id');
$attr = $(this).attr('data-attr');
// Check to see if this keyword has been used before
// because if not, we need to store an empty array there
if(typeof food[$name] === 'undefined'){
food[$name] = [];
}
// Add our element to that array
food[$name].push($attr);
});
关于javascript - 对象数组在 key 中存储相同的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35191205/