0
<table>
 <tbody>
  <tr>
   <td>
    <span class="big">Fruits</span>
   </td>
  </tr>
  <tr>
   <td>
    <span class="small">Apple</span>
   </td>
  </tr>
  <tr>
   <td>
    <span class="small">Apricot</span>
   </td>
  </tr>
  <tr>
   <td>
    <span class="small">Carrot</span>
   </td>
  </tr>
  <tr>
   <td>
    <span class="big">Colors</span>
   </td>
  <tr>
   <td>
    <span class="small">Red</span>
   </td>
  </tr>
  <tr>
   <td>
    <span class="small">Blue</span>
   </td>
  </tr>
 </tbody>
</table>

I have more than 10k tables like this, and need to parse them like

Fruits: Apple Apricot Carrot
Colors: Red Blue

Categories have different class names and objects have different class names, but they are all in the same table.

1
  • And the question is? Commented Aug 7, 2016 at 6:07

1 Answer 1

1

Here's my implementation:

var items = {};
var lastItem = null;

$('.big, .small').each(function() {
  var content = $(this).text();
  var cls = $(this).attr('class');

  if ( cls == 'big' )
  {
    lastItem = content;
    items[lastItem] = [];
    return;
  }

  items[lastItem].push(content);
});

console.log(items);

var items = {};
var lastItem = null;

$('.big, .small').each(function() {
  var content = $(this).text();
  var cls = $(this).attr('class');
  
  if ( cls == 'big' )
  {
    lastItem = content;
    items[lastItem] = [];
    return;
  }
  
  items[lastItem].push(content);
});

console.log(items);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
 <tbody>
  <tr>
   <td>
    <span class="big">Fruits</span>
   </td>
  </tr>
  <tr>
   <td>
    <span class="small">Apple</span>
   </td>
  </tr>
  <tr>
   <td>
    <span class="small">Apricot</span>
   </td>
  </tr>
  <tr>
   <td>
    <span class="small">Carrot</span>
   </td>
  </tr>
  <tr>
   <td>
    <span class="big">Colors</span>
   </td>
  <tr>
   <td>
    <span class="small">Red</span>
   </td>
  </tr>
  <tr>
   <td>
    <span class="small">Blue</span>
   </td>
  </tr>
 </tbody>
</table>

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

Comments

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.