Home > Software design >  return the element's data attributes in an object
return the element's data attributes in an object

Time:01-11

this is my code:

const dataset = (element) => {
  // TODO: return the element's data attributes in an object

};

I need to do this:

Implement the dataset function which takes one element parameter (of type String) and returns an Object with the right keys and values:

const burger = `<div  data-id="42" data-price="15" data-category="popular">
  <div >Popular</div>
  <div >
    <h2>The best burger in town (15€)</h2>
  </div>
</div>`;

dataset(burger);
// => { id: 42, price: 15, category: 'popular' }
  • It should only return the dataset of the wrapping element regardless of its children
  • It should cast the values to the right type (in the example, 42 and 15 should be numbers)

im really new and trying to learn as much as possible i don't have any clue on hoe to do this

CodePudding user response:

You can create an object from that html code then grab the dataset of the first child. While copying that, convert to int.

const burger = `<div  data-id="42" data-price="15" data-category="popular">
  <div >Popular</div>
  <div >
    <h2>The best burger in town (15€)</h2>
  </div>
</div>`;

const wrapper = document.createElement("div");
wrapper.innerHTML = burger;
const dataset = wrapper.firstElementChild.dataset;
const data = {};
for (const key in dataset) {
  data[key] = isNaN(dataset[key]) ? dataset[key] : Number(dataset[key]);
}
console.log(data);

CodePudding user response:

Simply write this way with reusable approach!

const dataset = ( element ) => {
  let tmpDiv = document.createElement('div');
      tmpDiv.innerHTML = element;
  let res = {
        id: tmpDiv.querySelector('.card').getAttribute('data-id'),
        price: tmpDiv.querySelector('.card').getAttribute('data-price') ,
        category: tmpDiv.querySelector('.card').getAttribute('data-category') 
      }
  return res
};



const burger = `<div  data-id="42" data-price="15" data-category="popular">
  <div >Popular</div>
  <div >
    <h2>The best burger in town (15€)</h2>
  </div>
</div>`;


console.log( dataset(burger) )

  • Related