我正在尝试使用每个循环递归创建一个jQuery对象数组。 如果key是相同的,我想用循环键创建另一个对象
我想知道等效的$array[] = $ariable -> '[]'
我有this jsfiddle。如何防止覆盖'abc'而是用具有相同键的def覆盖
var storevar = {}
$('.element').each(function(index, element) {
storevar[$(element).data('key')] = $(element).text()
});
console.log(storevar)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="results">
</div>
<span class="element" data-key="elementkey">abc</span>
<span class="element" data-key="elementkey">def</span>
<span class="element" data-key="elementkey1">ghi</span>
<span class="element" data-key="elementkey2">jkl</span>
// this is now
var wrong = {
elementkey: "def",
elementkey1: "ghi",
elementkey2: "jkl"
}
// what i want
var correct = {
elementkey: {
0: 'abc',
1: 'def'
},
elementkey1: "ghi",
elementkey2: "jkl"
}
答案 0 :(得分:0)
您可以检查您尝试写入的元素是否存在,如果不存在,请将其替换为数组并添加旧值和新值:
var storevar = {}
$('.element').each(function(index, element) {
var key = $(element).data('key');
var val = $(element).text();
if (typeof storevar[key] === "object") {
storevar[key].push(val);
} else if (storevar[key]) {
var oldVal = storevar[key];
storevar[key] = [];
storevar[key].push(oldVal);
storevar[key].push(val);
} else {
storevar[key] = val;
}
});
console.log(storevar)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="results">
</div>
<span class="element" data-key="elementkey">abc</span>
<span class="element" data-key="elementkey">def</span>
<span class="element" data-key="elementkey1">ghi</span>
<span class="element" data-key="elementkey2">jkl</span>