How to create auto key for jQuery object array in loop

I'm trying to create a jQuery object array recursive using each loop. If key is the same I want to create another object with loop key

I want to know what is the equivalent $array[] = $ariable -> '[]'

I have this jsfiddle. How to prevent overwrite 'abc' instead overwrite with def which has same key

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"
}

Answers 1

  • You can check if the element you are trying to write to exist, and if not, replace it by an array and add both the old value and the new value:

    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>


Related Articles