Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

283
Visualizações
How do I create an object containing each letter of a data attribute as well as the position of that letter of the alphabet

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);
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

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>

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>

about 4 years ago · Juan Pablo Isaza Relatório

0

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>

about 4 years ago · Juan Pablo Isaza Relatório

0

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);
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda