-1

I recieved li tag from html

<li data-group="man">
    <span>15</span>
    <h5>alex</h5>
</li>
<li data-group="man">
    <span>20</span>
    <h5>jack</h5>
</li>
<li data-group="man">
    <span>30</span>
    <h5>john</h5>
</li>
<li data-group="woman">
    <span>25</span>
    <h5>Kianna</h5>
</li>
<li data-group="woman">
    <span>17</span>
    <h5>ela</h5>
</li>
<li data-group="woman">
    <span>25</span>
    <h5>Emery</h5>
</li>

I want to produce li using foreach and than convert them into an object if they have the same data-group.

    "man":{
        "alex":15,
        "jack":20,
        "john":30
    },
    "woman":{
        "Kianna":25,
        "ela":17,
        "Emery":25
    }

Finally, they should be assigned to an empty object

objects should not be as forms of 0,1,2...

cfarhad
  • 168
  • 10
  • you can look at this answer which can be helpful [Link](https://stackoverflow.com/questions/4146502/jquery-selectors-on-custom-data-attributes-using-html5) – Hasa N Mar 06 '21 at 18:57

1 Answers1

1

Use document.querySelectorAll('[data-group]') to get all items with a [data-group] tag. Spread the NodeList to an array, and reduce the array to the object:

const result = [...document.querySelectorAll('[data-group]')]
  .reduce((acc, el) => ({
    ...acc,
    [el.dataset.group]: {
      ...acc[el.dataset.group],
      [el.children[1].textContent]: +el.children[0].textContent
    }
  }), {})
  
console.log(result)
ul { visibility: hidden; }
.as-console-wrapper { max-height: 100% !important; top: 0; }
<ul> <li data-group="man"> <span>15</span> <h5>alex</h5> </li><li data-group="man"> <span>20</span> <h5>jack</h5> </li><li data-group="man"> <span>30</span> <h5>john</h5> </li><li data-group="woman"> <span>25</span> <h5>Kianna</h5> </li><li data-group="woman"> <span>17</span> <h5>ela</h5> </li><li data-group="woman"> <span>25</span> <h5>Emery</h5> </li></ul>

You can also use NodeList.forEach() to create the object:

const result = {}

document.querySelectorAll('[data-group]')
  .forEach(el => {
    const { group } = el.dataset
    const [value, key] = el.children
    
    if(!result[group]) result[group] = {}
    
    result[group][key.textContent] = +value.textContent
  })
  
console.log(result)
ul { visibility: hidden; }
.as-console-wrapper { max-height: 100% !important; top: 0; }
<ul> <li data-group="man"> <span>15</span> <h5>alex</h5> </li><li data-group="man"> <span>20</span> <h5>jack</h5> </li><li data-group="man"> <span>30</span> <h5>john</h5> </li><li data-group="woman"> <span>25</span> <h5>Kianna</h5> </li><li data-group="woman"> <span>17</span> <h5>ela</h5> </li><li data-group="woman"> <span>25</span> <h5>Emery</h5> </li></ul>
Ori Drori
  • 183,571
  • 29
  • 224
  • 209