PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label nested-lists. Show all posts
Showing posts with label nested-lists. Show all posts

Monday, July 25, 2022

[FIXED] How to dynamically create a table from a JSON with nested lists using Javascript?

 July 25, 2022     html, html-table, javascript, json, nested-lists     No comments   

Issue

I'm trying to create an HTML table from a JSON file which values can include nested lists.

Example:

{
     "entry 1":[
         ["text1", "text2", "text3"],
         ["text4", "text5", "text6"],
         ["text7", "text8", "text9"]
    ],
    "entry 2": "N/A",
    "entry 3": [
         ["text1", "text2", "text3"],
         ["text4", "text5", "text6"]
    ],
    "entry 4": [
         ["text1", "text2"],
         ["text3", "text4"]
    ]
}

My goal is to create an HTML table with a predefined header for the two columns:

  • header_title_1
  • header_title_2

That will never change, and the table should look like this:

table_example

Thanks for your help !


Solution

Using the for...in iterator on the object to get the key. I created a row for each property, then a cell for the key and value. Then if the value isn't an array, like the entry2 key, we make it an array to iterate through the elements.

Creating a new row for each element in the array and creating a new cell for the items in the array. If it is an array, the value would be converted to a string separated by the comma ',' or it would be set just as it is.

Then we append the elements to the body of the table.

const tbody = document.getElementById('table').tBodies[0];
const obj = {"entry 1":[["text1","text2","text3"],["text4","text5","text6"],["text7","text8","text9"]],"entry 2":"N/A","entry 3":[["text1","text2","text3"],["text4","text5","text6"]],"entry 4":[["text1","text2"],["text3","text4"]]};

function createTable(obj) {
  tbody.innerHTML = ''; // To reset the table
  
  for (const key in obj) {
    if (!obj.hasOwnProperty(key)) continue;
    const value = Array.isArray(obj[key]) ? obj[key] : [obj[key]];
    const row = document.createElement('tr');
    const key_cell = Object.assign(document.createElement('td'), {
      innerText: key
    });
    const value_column = Object.assign(document.createElement('td'), {
      innerText: value.splice(0, 1)[0]
    });

    row.append(...[key_cell, value_column]);
    tbody.append(row);

    value.forEach(val => {
      const inner_row = document.createElement('tr');
      const empty_key_cell = document.createElement('td');
      const value_cell = Object.assign(document.createElement('td'), {
        innerText: val
      });
      inner_row.append(...[empty_key_cell, value_cell]);
      tbody.append(inner_row);
    });
  }
}

createTable(obj);
<table id="table" border="1" width="100%">
  <thead>
    <td>header_title_1</td>
    <td>header_title_2</td>
  </thead>
  <tbody></tbody>
</table>



Answered By - a.mola
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, July 21, 2022

[FIXED] How to iterate through sequential string values and append to a nested list

 July 21, 2022     append, list, nested-lists, python, string     No comments   

Issue

I have a list containing filenames of a dataset, in the form of a number followed by some descriptive text (which is different for each file):

a = ['001_sometext', '002_sometext', ..., '162_sometext', '001_sometext', ..., '162_sometext]

The list cycles from '001' to '162' multiple times, but the list also doesn't follow a perfect sequence, some numbers are missing.

My intention is to read all files containing '001' and append them to another list, and then do the same for '002' and so on, such that I end up with a nested list containing a separate list for each number in the sequence.

My current attempt:

phrases = []
xi = []
for digits in range(0, 162):
    for x in a:
        if str(digits) in x:
            xi.append(x)
    phrases.append(xi)

However, this gives me a nested list of the entire list over and over again, rather than a list for each number.

Edit:

The loop above is reading all files containing just a '0', which brings back hundreds of files and adds them to a list. A minor fix is that I've made a loop for each order of magnitude:

phrases = []
for digits in range(1, 10):
    xi = []
    for x in a:
        if '00' + str(digits) in x:
            xi.append(x)
        else: None
    phrases.append(xi)

and

phrases = []
for digits in range(10, 100):
    xi = []
    for x in a:
        if '0' + str(digits) in x:
            xi.append(x)
        else: None
    phrases.append(xi)

and

phrases = []
for digits in range(100, 162):
    xi = []
    for x in a:
        if str(digits) in x:
            xi.append(x)
        else: None
    phrases.append(xi)

Solution

You have a few issues with your code, firstly you need to clear xi on each loop; then you need to iterate in the range 1 to 163 (i.e. 1 to 162 inclusive) and finally you can't use str(digits) in x because (for example) str(1) would match against 001, 015, 102 etc.

Something like this should work:

for digits in range(1, 163):
    xi = []
    srch = f'{digits:03d}'
    for x in a:
        if x.startswith(srch):
            xi.append(x)
    phrases.append(xi)

Alternatively you could use a nested list comprehension:

phrases = [ [f for f in a if f.startswith(f'{n:03d}')] for n in range(1, 163)]

If

a = ['001_sometext', '002_sometext', '162_sometext', '001_someothertext', '162_someothertext']

both of these give a result of:

[['001_sometext', '001_someothertext'], ['002_sometext'], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], ['162_sometext', '162_someothertext']]


Answered By - Nick
Answer Checked By - Senaida (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home
View mobile version

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing