0

I have a number of data-attributes on page which will have different values, but there will be duplicates of these values, for example:

<div data-user-val="[Adult-Young-25]"></div>
<div data-user-val="[Adult-Young-25]"></div>
<div data-user-val="[Adult-Young-25]"></div>
<div data-user-val="[Adult-Mid-35]"></div>
<div data-user-val="[Adult-Mid-35]"></div>
<div data-user-val="[Adult-Old-75]"></div>

I want to loop through and grab each unique value ('[Adult-Young-25]','[Adult-Mid-35]','[Adult-Old-75]') and split these up to pass to an array as key-value pairs like:

var array = {"Adult Young": "25", "Adult Mid": "35", "Adult Old": "75"};

I'm struggling to 1. grab one instance of each repeated data value, and 2. to 'split' the value to map as key-value pairs.

6
  • Post some code that you have tried and perhaps not working Commented Apr 30, 2018 at 9:28
  • It works if all attributes have the same amounts of delimiters (here -). Yet I would recommend to use the actual attribute name (data-adult-young, data-adult-mid) as attribute name with the actual value (25, 35, 75) instead. Would make it much easier. Commented Apr 30, 2018 at 9:32
  • @Lain the structure of the data attribute is unfortunately out of my control, so I need to work with [Adult-Young-25] for example. Commented Apr 30, 2018 at 9:33
  • Can there be a [Adult-Young-26]? Commented Apr 30, 2018 at 9:36
  • @Lain absolutely there could be. That's why I need to ensure I grab each unique value only once. Commented Apr 30, 2018 at 9:37

3 Answers 3

2

var obj = {};

$('div').each(function(){
  var data_attrivute_value = $(this).data('user-val');
  data_attrivute_value = data_attrivute_value.substring(1,data_attrivute_value.lastIndexOf("]"));
  var exploded_string = data_attrivute_value.split('-');
  obj[exploded_string[0]+' '+exploded_string[1]] = exploded_string[2];
});

console.log(obj);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-user-val="[Adult-Young-25]"></div>
<div data-user-val="[Adult-Young-25]"></div>
<div data-user-val="[Adult-Young-25]"></div>
<div data-user-val="[Adult-Mid-35]"></div>
<div data-user-val="[Adult-Mid-35]"></div>
<div data-user-val="[Adult-Old-75]"></div>

Sign up to request clarification or add additional context in comments.

Comments

0

Use document.querySelectorAll() to get all elements with the data-user-val attribute, and spread to array. Iterate the array with Array.reduce(), and get the value of the attribute. Use String.match() to get the non numeric (key) and the numeric (value) parts of the value. Assign the key and value to the object.

const result = [...document.querySelectorAll('[data-user-val]')]
  .reduce((r, el) => {
    const [, k, v] = el.getAttribute('data-user-val').match(/([^\d\[]+)(\d+)/);
    
    r[k.replace(/-/g, ' ').trim()] = v;
    
    return r;
  }, {});
  
console.log(result);
<div data-user-val="[Adult-Young-25]"></div>
<div data-user-val="[Adult-Young-25]"></div>
<div data-user-val="[Adult-Young-25]"></div>
<div data-user-val="[Adult-Mid-35]"></div>
<div data-user-val="[Adult-Mid-35]"></div>
<div data-user-val="[Adult-Old-75]"></div>

Comments

0

Here's a simple solution without any fancy libraries or functions:

var divs = document.getElementsByTagName('div');
var myAttr = 'data-user-val';
var dict = {};

for(i = 0; i < divs.length; i++) {
  var val = divs[i].getAttribute(myAttr);
  if (val) {
    var trimmed = val.substr(1, val.length - 2)
    var splitted = trimmed.split('-');
    var key = splitted[0] + ' ' + splitted[1];
    if (!dict.hasOwnProperty(key)) {
      dict[key] = splitted[2];
    }
  }
}

6 Comments

The code would fail if one div in the whole document did not have an attribute called 'data-user-val'.
true, fixed now
Why not just only select the correct divs? Looping through 1000 divs takes alot more time than just ~10 :-)
because getElementsByTagName is more reliable than querySelectorAll, as it's updated every time you check the value. So if there would be an update from backend and you'll get more divs, then my code will correctly update the dict.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.