亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用數組值創建對象

使用數組值創建對象

不負相思意 2024-01-18 16:57:21
我正在嘗試創建一個具有多個子對象的對象數組。我有一個包含如下數據的表:| PARENT   | CHILD  |---------------------| 123456   | 123    || 123456   | 124    || 123456   | 125    || 123457   | 345    || 123457   | 346    || 123457   | 347    |....我希望得到一個與此類似的數組:var arr_nos = { 123456 : [123, 124, 125], 123457 : [345, 346, 347]}在循環期間,我有這個:var arr_nos = [];$('#table tbody tr').each(function( index ) {   var parent_no = elem.find('.parent_no').html();   var child_id = elem.find('.child_id ').html();   if(parent_no != '') {      child = [         child_id      ]      arr_nos.push(parent_no, child);   }});但這會導致:["123456", Array(1), "123456", Array(1),"123456", Array(1), "123457", Array(1), "123457", Array(1), "123457", Array(1)]
查看完整描述

3 回答

?
慕尼黑5688855

TA貢獻1848條經驗 獲得超2個贊

您可以使用這個循環:


var arr_nos = {};

$('#table tbody tr').each(function( index,elem ) {

   var parent_no = $(elem).find('.parent_no').html();

   var child_id = $(elem).find('.child_id ').html();

   if(parent_no != '') {

      if(!arr_nos[parent_no]) arr_nos[parent_no] = [];

      arr_nos[parent_no].push(child_id);

   }


});


console.log(arr_nos);

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<table id="table">

 <tbody>

  <tr>

    <th class='parent_no'>1</th>

    <th class='child_id'>11</th>

  </tr>

  <tr>

    <th class='parent_no'>2</th>

    <th class='child_id'>22</th>

  </tr>

  <tr>

    <th class='parent_no'>3</th>

    <th class='child_id'>33</th>

  </tr>

  <tr>

    <th class='parent_no'>2</th>

    <th class='child_id'>444</th>

  </tr>

  </tbody>

</table>


查看完整回答
反對 回復 2024-01-18
?
交互式愛情

TA貢獻1712條經驗 獲得超3個贊

代替:

var arr_nos = []
arr_nos.push(parent_no, child)

做:

let arr_nos = {}
arr_nos[parent_no] = [...arr_nos[parent_no], child]


查看完整回答
反對 回復 2024-01-18
?
慕容3067478

TA貢獻1773條經驗 獲得超3個贊

要獲取示例中的數組對象,您必須執行以下操作

  arr_nos[parent_no] = child

并且必須將對象聲明為

arr_nos = {}

代替

arr_nos = []

但這是數組的對象,而不是對象的數組。要么你的例子錯了,要么你的定義錯了

我不確定如何獲取您的具體示例{123456: [123, 124, 125], 123457: [345, 346, 347]}。您必須指定必須制定什么標準來決定該對象的鍵是什么。


查看完整回答
反對 回復 2024-01-18
  • 3 回答
  • 0 關注
  • 163 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號