Search code examples
javascriptjqueryjavascript-objectsassociative-array

How do I create and modify an associative array in JavaScript?


I'm trying to move some code from server side to client side. I'm struggling to work with Javascript. It seeems what I need to achieve uses objects vs arrays.

I have some input fields with data attributes that I loop through.

$(".selection:checked").each(function(){

    $selection_id=$(this).data('selection_id');
    $swatch_id=$(this).data('swatch_id');

});

Firstly, I want to create an array in the following form:

$array[$selection_id]=$swatch_id;

ie array(100=>123,200=456,300=789)

Secondly, I want to loop through a list of elements and swap out a value according to the array key.

ie element has key 100 and value 1000 then:

$array[100]=1000;

New array is array(100=>1000,200=456,300=789)

Finally, I need to take that array and turn it into a string in the form:

"100:1000,200:456,300:789"

I'm new to Javascript and still struggling to get my head around objects. Any help is appreciated.


Solution

  • You better create an object for storing the $selection_id => $watch_id mapping. You can achieve it using following syntax

    const mapping = {};
    mapping[$selection_id] = $watch_id;
    

    Then this array(100=>123,200=456,300=789) will look like

    mapping = {
       100: 123,
       200: 456,
       300: 789
    }
    

    Values Can be accessed using mapping[100] which will give you 123. If you want to convert it into string like you specified do the following.

    const mapString = Object.keys(mapping).reduce((acc, curr) =>
      `${acc}${curr}:${mapping[curr]},`,
    "").slice(0, -1)
    

    It will give you this output "100:123,200:456,300:789"

    Update

    For generating mapString, use the following. Thanks, @Soc for the suggestion.

    const mapString = Object.keys(mapping).map(key => `${key}:${mapping[key]}`).join(',');