Как преобразовать значение из таблицы HTML в массив JSON в javascript

#javascript #html

Вопрос:

     <table style="width:100%;   border-collapse: collapse;  text-align: center;" id="stockinboundedittable">
      
        <tr>
          <th style="display:none;">subcategory</th>
          <th>Sl.No</th>
          <!--<th>I.U.Code</th>-->
          <th>Item Name</th>
          <th> old stock</th>
          <th> new stock</th>
          <th> Total Stock</th>
          <th> qrt</th>
          <th>Edit</th>
        </tr>
     
      <tr>
        <td style="display:none;">tmcsubctgy_2</td>
        <td>
          <input style="    width: 100%;" id="slno1editinbound1" value="1" readonly="">
        </td>
        <td>
          <input style="    width: 100%;" id="stockinboundedititemname1" value="Fresh Goat Meat - Curry Cut" readonly="">
        </td>
        <td>
          <input style="    width: 100%;" id="stockinboundeditoldstock1" value="20" readonly="">
        </td>
        <td>
          <input style="    width: 100%;" id="stockinboundeditnewstock1" value="10" readonly="">
        </td>
        <td>
        <input style="    width: 100%;" id="stockinboundedittotalstock1" value="30" readonly="">
        </td>
        <td>
          <input style="    width: 100%;" id="inboundeditqty1">
        </td>
        <td>
          <button style="background: #fdd110; width: 100%;" id="stockinboundeditditbut1">EDIT</button>
        </td>
      </tr>
      <tr>
        <td style="display:none;">tmcsubctgy_5</td>
        <td>
          <input style="    width: 100%;" id="slno1editinbound2" value="2" readonly="">
        </td>
        <td>
          <input style="    width: 100%;" id="stockinboundedititemname2" value="Everest - Kasur Methi" readonly="">
        </td>
        <td>
          <input style="    width: 100%;" id="stockinboundeditoldstock2" value="0" readonly="">
        </td>
        <td>
          <input style="    width: 100%;" id="stockinboundeditnewstock2" value="10" readonly="">
        </td>
        <td>
        <input style="    width: 100%;" id="stockinboundedittotalstock2" value="10" readonly="">
        </td>
        <td>
          <input style="    width: 100%;" id="inboundeditqty2">
        </td>
        <td>
          <button style="background: #fdd110; width: 100%;" id="stockinboundeditditbut2">EDIT</button>
        </td>
      </tr>
      <tr>
        <td style="display:none;">tmcsubctgy_13</td>
        <td>
          <input style="    width: 100%;" id="slno1editinbound3" value="3" readonly="">
        </td>
        <td>
          <input style="    width: 100%;" id="stockinboundedititemname3" value="Fresh Coconut Milk 150 ml" readonly="">
        </td>
        <td>
          <input style="    width: 100%;" id="stockinboundeditoldstock3" value="10" readonly="">
        </td>
        <td>
          <input style="    width: 100%;" id="stockinboundeditnewstock3" value="10" readonly="">
        </td>
        <td>
        <input style="    width: 100%;" id="stockinboundedittotalstock3" value="20" readonly="">
        </td>
        <td>
          <input style="    width: 100%;" id="inboundeditqty3">
        </td>
        <td>
          <button style="background: #fdd110; width: 100%;" id="stockinboundeditditbut3">EDIT</button>
        </td>
      </tr>
      <tr>
        <td style="display:none;">tmcsubctgy_5</td>
        <td>
          <input style="    width: 100%;" id="slno1editinbound4" value="4" readonly="">
        </td>
        <td>
          <input style="    width: 100%;" id="stockinboundedititemname4" value="Sakthi - Chicken Masala" readonly="">
        </td>
        <td>
          <input style="    width: 100%;" id="stockinboundeditoldstock4" value="20" readonly="">
        </td>
        <td>
          <input style="    width: 100%;" id="stockinboundeditnewstock4" value="10" readonly="">
        </td>
        <td>
        <input style="    width: 100%;" id="stockinboundedittotalstock4" value="30" readonly="">
        </td>
        <td>
          <input style="    width: 100%;" id="inboundeditqty4">
        </td>
        <td>
          <button style="background: #fdd110; width: 100%;" id="stockinboundeditditbut4">EDIT</button>
        </td>
      </tr>
      <tr>
        <td style="display:none;">tmcsubctgy_2</td>
        <td>
          <input style="    width: 100%;" id="slno1editinbound5" value="5" readonly="">
        </td>
        <td>
          <input style="    width: 100%;" id="stockinboundedititemname5" value="Goat Bones - Regular Soup Pack" readonly="">
        </td>
        <td>
          <input style="    width: 100%;" id="stockinboundeditoldstock5" value="0" readonly="">
        </td>
        <td>
          <input style="    width: 100%;" id="stockinboundeditnewstock5" value="10" readonly="">
        </td>
        <td>
        <input style="    width: 100%;" id="stockinboundedittotalstock5" value="10" readonly="">
        </td>
        <td>
          <input style="    width: 100%;" id="inboundeditqty5">
        </td>
        <td>
          <button style="background: #fdd110; width: 100%;" id="stockinboundeditditbut5">EDIT</button>
        </td>
      </tr>
      </table>
    </table>

 

##мне нужно прочитать значения внутри тега и сохранить его как массив json с sl.no и кнопка редактирования исключена из массива json##

 [{"itemname":"Chicken Drumstick","oldstock":"20","newstock":"10","totalstock":"30"},
{"itemname":"Chicken Drumstick","oldstock":"0","newstock":"10","totalstock":"10"},
{"itemname":"Chicken Drumstick","oldstock":"10","newstock":"10","totalstock":"20"},
{"itemname":"Chicken Drumstick","oldstock":"20","newstock":"10","totalstock":"30"},
{"itemname":"Chicken Drumstick","oldstock":"0","newstock":"10","totalstock":"10"}]
 

*приведенный выше массив json-это пример формата, который мне нужен

  • мне нужно прочитать его с циклом из всей таблицы

Комментарии:

1. Вы действительно хотите, чтобы он был в виде JSON или в виде массива объектов JS?

2. [{«наименование товара»:»Куриная ножка»,»олдсток»:»20″,»ньюсток»:»10″,»общий запас»:»30″}, {«наименование товара»:»Куриная ножка»,»олдсток»:»0″,»ньюсток»:»10″,»общий запас»:»10″}, {«наименование товара»:»Куриная ножка»,»олдсток»:»10″,»новый запас»:»10″,»общий запас»:»20″}, {«наименование товара»:»Куриная ножка»,»старый запас»:»20″,»новый запас»:»10″,»общий запас»:»30″}, {«наименование товара»:»Куриная ножка»,»старый запас»:»0″,»новый запас»:»10″,»общий запас»:»10″}]. Мне нравится иметь такие данные

3. Извините, но это не ответ на вопрос?

Ответ №1:

Это сделает свою работу:

 const res=[...document.querySelectorAll("#stockinboundedittable tr")].slice(1).map(tr=>
[...tr.querySelectorAll("input")].slice(0).map(inp=>[inp.id.replace(/.*inboundedit/,"").replace(/d $/,""),inp.value]))
.reduce((a,c)=>{
  a[c[0][1]]=
  Object.fromEntries(c.slice(1));
  return a},{}); 

console.log(res[2]);
   
 <table style="width:100%;   border-collapse: collapse;  text-align: center;" id="stockinboundedittable">
  
    <tr>
      <th style="display:none;">subcategory</th>
      <th>Sl.No</th>
      <!--<th>I.U.Code</th>-->
      <th>Item Name</th>
      <th> old stock</th>
      <th> new stock</th>
      <th> Total Stock</th>
      <th> qrt</th>
      <th>Edit</th>
    </tr>
 
  <tr>
    <td style="display:none;">tmcsubctgy_2</td>
    <td>
      <input style="    width: 100%;" id="slno1editinbound1" value="1" readonly="">
    </td>
    <td>
      <input style="    width: 100%;" id="stockinboundedititemname1" value="Fresh Goat Meat - Curry Cut" readonly="">
    </td>
    <td>
      <input style="    width: 100%;" id="stockinboundeditoldstock1" value="20" readonly="">
    </td>
    <td>
      <input style="    width: 100%;" id="stockinboundeditnewstock1" value="10" readonly="">
    </td>
    <td>
    <input style="    width: 100%;" id="stockinboundedittotalstock1" value="30" readonly="">
    </td>
    <td>
      <input style="    width: 100%;" id="inboundeditqty1">
    </td>
    <td>
      <button style="background: #fdd110; width: 100%;" id="stockinboundeditditbut1">EDIT</button>
    </td>
  </tr>
  <tr>
    <td style="display:none;">tmcsubctgy_5</td>
    <td>
      <input style="    width: 100%;" id="slno1editinbound2" value="2" readonly="">
    </td>
    <td>
      <input style="    width: 100%;" id="stockinboundedititemname2" value="Everest - Kasur Methi" readonly="">
    </td>
    <td>
      <input style="    width: 100%;" id="stockinboundeditoldstock2" value="0" readonly="">
    </td>
    <td>
      <input style="    width: 100%;" id="stockinboundeditnewstock2" value="10" readonly="">
    </td>
    <td>
    <input style="    width: 100%;" id="stockinboundedittotalstock2" value="10" readonly="">
    </td>
    <td>
      <input style="    width: 100%;" id="inboundeditqty2">
    </td>
    <td>
      <button style="background: #fdd110; width: 100%;" id="stockinboundeditditbut2">EDIT</button>
    </td>
  </tr>
  <tr>
    <td style="display:none;">tmcsubctgy_13</td>
    <td>
      <input style="    width: 100%;" id="slno1editinbound3" value="3" readonly="">
    </td>
    <td>
      <input style="    width: 100%;" id="stockinboundedititemname3" value="Fresh Coconut Milk 150 ml" readonly="">
    </td>
    <td>
      <input style="    width: 100%;" id="stockinboundeditoldstock3" value="10" readonly="">
    </td>
    <td>
      <input style="    width: 100%;" id="stockinboundeditnewstock3" value="10" readonly="">
    </td>
    <td>
    <input style="    width: 100%;" id="stockinboundedittotalstock3" value="20" readonly="">
    </td>
    <td>
      <input style="    width: 100%;" id="inboundeditqty3">
    </td>
    <td>
      <button style="background: #fdd110; width: 100%;" id="stockinboundeditditbut3">EDIT</button>
    </td>
  </tr>
  <tr>
    <td style="display:none;">tmcsubctgy_5</td>
    <td>
      <input style="    width: 100%;" id="slno1editinbound4" value="4" readonly="">
    </td>
    <td>
      <input style="    width: 100%;" id="stockinboundedititemname4" value="Sakthi - Chicken Masala" readonly="">
    </td>
    <td>
      <input style="    width: 100%;" id="stockinboundeditoldstock4" value="20" readonly="">
    </td>
    <td>
      <input style="    width: 100%;" id="stockinboundeditnewstock4" value="10" readonly="">
    </td>
    <td>
    <input style="    width: 100%;" id="stockinboundedittotalstock4" value="30" readonly="">
    </td>
    <td>
      <input style="    width: 100%;" id="inboundeditqty4">
    </td>
    <td>
      <button style="background: #fdd110; width: 100%;" id="stockinboundeditditbut4">EDIT</button>
    </td>
  </tr>
  <tr>
    <td style="display:none;">tmcsubctgy_2</td>
    <td>
      <input style="    width: 100%;" id="slno1editinbound5" value="5" readonly="">
    </td>
    <td>
      <input style="    width: 100%;" id="stockinboundedititemname5" value="Goat Bones - Regular Soup Pack" readonly="">
    </td>
    <td>
      <input style="    width: 100%;" id="stockinboundeditoldstock5" value="0" readonly="">
    </td>
    <td>
      <input style="    width: 100%;" id="stockinboundeditnewstock5" value="10" readonly="">
    </td>
    <td>
    <input style="    width: 100%;" id="stockinboundedittotalstock5" value="10" readonly="">
    </td>
    <td>
      <input style="    width: 100%;" id="inboundeditqty5">
    </td>
    <td>
      <button style="background: #fdd110; width: 100%;" id="stockinboundeditditbut5">EDIT</button>
    </td>
  </tr>
  </table>
</table> 

У меня есть вложенный .map() цикл, который будет собирать как id s, так и value s каждого поля ввода (кроме первого в каждой строке). Затем Object.fromEntries() вызов соберет внутренние массивы обратно в объекты, используя первый элемент массива в качестве ключа, а второй-в качестве значения.

Мой ответ также возвращает не строку JSON, а массив объектов. Просто введите его, JSON.stringify() если вам действительно нужна строка JSON.

Обновить
После последних комментариев ОП я обновил свой ответ. Теперь я использую первый столбец в качестве «идентификатора-ключа» и создаю объект объектов вместо массива объектов. Id-ключ можно использовать для обращения к каждому меню в отдельности, как видно из моего примера console.log() , где я выбрал меню с помощью Id-ключа 2 .

Комментарии:

1. это работает отлично , как я могу получить только первую строку или вторую строку с идентификатором строки ……

2. Я обновил свой ответ.

Ответ №2:

Вы можете попробовать это:

    function table_to_array(table_id) {
            myData = document.getElementById(table_id).rows
            //console.log(myData)
            my_liste = []
            for (var i = 0; i < myData.length; i  ) {
                    el = myData[i].children
                    my_el = []
                    for (var j = 0; j < el.length; j  ) {
                            my_el.push(el[j].innerText);
                    }
                    my_liste.push(my_el)

            }
            return my_liste
    }
 

Комментарии:

1. Не могли бы вы подождать, пока ОП прояснит этот вопрос? Это не возвращает JSON.

2. [{«наименование товара»:»Куриная ножка»,»олдсток»:»20″,»ньюсток»:»10″,»общий запас»:»30″}, {«наименование товара»:»Куриная ножка»,»олдсток»:»0″,»ньюсток»:»10″,»общий запас»:»10″}, {«наименование товара»:»Куриная ножка»,»олдсток»:»10″,»новый запас»:»10″,»общий запас»:»20″}, {«наименование товара»:»Куриная ножка»,»старый запас»:»20″,»новый запас»:»10″,»общий запас»:»30″}, {«наименование товара»:»Куриная ножка»,»старый запас»:»0″,»новый запас»:»10″,»общий запас»:»10″}]. Мне нравится иметь данные в таком формате, как массив json или объекты

3. @A. Chithrai вам нужны данные в формате JS или в виде строки?