Home > Net >  How do I create an object containing each letter of a data attribute as well as the position of that
How do I create an object containing each letter of a data attribute as well as the position of that

Time:10-27

I am currently doing a coding challenge where I have to write a jQuery function to get the value of the data parameter of each div below, and create an object containing each letter as well as the position of that letter of the alphabet.

<div class="foo" data-widget="bar">This</div>
<div class="foo" data-widget="baz">That</div>

The output should be:

This: {"b":"2", "a":"1", "r":"18"}
That: {"b":"2", "a":"1", "z":"26"}

So far this is what I have:

var allAttributes = $('.foo').map(function() {
  return $(this).attr('data-widget');
}).get();

console.log(allAttributes);

//this function finds the numerical position of the letters in a string
var alphabet = "abcdefghijklmnopqrstuvwxyz".split('');
var alphabetPosition = text => 
  text.split('').map(x => alphabet.indexOf(x)   1);

CodePudding user response:

To construct the object for each div, you can get the item's data-widget attribute value, split into an array of characters, map through each and construct an array containing the letter and its index in alphabet, then use Object.fromEntries to convert into an object.

var alphabet = "abcdefghijklmnopqrstuvwxyz".split('');

const obj = {}

$('.foo').each(function(){
  obj[this.textContent] = Object.fromEntries(this.dataset.widget.split('').map(e => [e, alphabet.indexOf(e)   1]))
})

console.log(obj)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="foo" data-widget="bar">This</div>
<div class="foo" data-widget="baz">That</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Consider the following.

$(function() {
  var myText = {};

  function charPos(c) {
    var alphabet = "abcdefghijklmnopqrstuvwxyz".split('');
    return alphabet.indexOf(c)   1;
  }

  function wordDetails(w) {
    var r = {};
    $.each(w.split(""), function(i, c) {
      r[c] = charPos(c.toString());
    });
    return r;
  }

  $(".foo").each(function(i, el) {
    myText[$(el).text().trim()] = wordDetails($(el).data("widget"));
  });
  console.log(myText);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="foo" data-widget="bar">This</div>
<div class="foo" data-widget="baz">That</div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Result:

{
  "This": {
    "b": 2,
    "a": 1,
    "r": 18
  },
  "That": {
    "b": 2,
    "a": 1,
    "z": 26
  }
}

If you want to minimize it:

$(function() {
  var myText = {};

  $(".foo").each(function(i, el) {
    var obj = {};
    $.each($(el).data("widget").split(""), function() {
      obj[this] = "abcdefghijklmnopqrstuvwxyz".split('').indexOf(this.toString())   1;
    });
    myText[$(el).text().trim()] = obj;
  });

  console.log(myText);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="foo" data-widget="bar">This</div>
<div class="foo" data-widget="baz">That</div>
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

I accept your challenge, however after completing it I realized you did say JQuery and this solution is just Javascript.

Check out my solution here: CodePen

let elements = document.querySelectorAll(".foo");
let alph = 'abcdefghijklmnopqrstuvwxyz'.split('');
let result = {};
Array.from(elements).map(e => {
  let key = e.innerText;
  let value = {};
  let data = e.dataset.widget.split('');
  data.map( c => value[c] = alph.indexOf(c)   1 );
  result[key] = value;
})
console.log(result);

CodePudding user response:

you can do that...
with the help of Array.reduce()

const
  alphabet = ' abcdefghijklmnopqrstuvwxyz'
, result =
    Array
    .from(document.querySelectorAll('.foo'))
    .reduce( (res,e) => 
      {
      res[e.textContent] = 
        [...e.dataset.widget]
        .reduce( (r,c) =>
          (r[c] = alphabet.indexOf(c).toString(10), r )
        ,{})
      return res
      },{})
 
const // show result
  rpl  = [[`"`,`'`],[`}`,` }`],[`{`,`{ `],[`:`,`: `],[`},`,`}\n,`],[`,`,`, `],[`} }`,`}\n}`]]
, clog = s => rpl.reduce((r,[x,y])=>r.replaceAll(x,y),s)

console.log( clog(JSON.stringify(result)) )
.as-console-wrapper { max-height: 100% !important; top: 0 }
<div class="foo" data-widget="bar">This</div>
<div class="foo" data-widget="baz">That</div>
<iframe name="sif4" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related