在JavaScript中处理数组值

时间:2019-09-13 13:47:38

标签: javascript jquery arrays

我有以下数组

var my_arry =
      { "Description": "Actual Opening stock"
      , "Fri 05-Aug": "<input type='text' class='form-control' value='600'>"
      , "Mon 01-Aug": "<input type='text' class='form-control' value='200'>"
      , "Thu 04-Aug": "<input type='text' class='form-control' value='500'>"
      } 

我要遍历此过程并像下面这样格式化数组

var my_arry = 
      { "Description": "Actual Opening stock"
      , "Fri 05-Aug" : "600"
      , "Mon 01-Aug" : "200"
      , "Thu 04-Aug" : "500"
      } 

基本上从输入标签中获取值

我使用了以下内容,但没有用

$.each( my_arry, function( key, value ) {
                    console.log(value.find('input').val())
                 });

我可以通过其他任何方式

2 个答案:

答案 0 :(得分:1)

与本地JS相同(没有jQuery)

const my_arry =
        { "Description": "Actual Opening stock"
        , "Fri 05-Aug": "<input type='text' class='form-control' value='600'>"
        , "Mon 01-Aug": "<input type='text' class='form-control' value='200'>"
        , "Thu 04-Aug": "<input type='text' class='form-control' value='500'>"
        } 

const parser = new DOMParser()

var rep = {}
for(let elm in my_arry)
  {
  if (elm === 'Description')
    {
    rep[elm] = my_arry[elm]
    }
   else
    {
    let doc  = parser.parseFromString(my_arry[elm], "text/html")
    rep[elm] =  doc.querySelector('input').value
    }
  }

console.log( rep )

对象真实数组的其他情况

const my_arry = 
  [ { "Description": "Actual Opening stock",   "Fri 05-Aug" : "<input type='text' class='form-control' value='600'>" } 
  , { "Description": "closing Opening stock ", "Fri 05-Aug" : "<input type='text' class='form-control' value='600'>" } 
  ]

const parser = new DOMParser()

for(let elm of my_arry)
  {
  let doc  = parser.parseFromString(elm['Fri 05-Aug'], "text/html")
  elm['Fri 05-Aug'] = doc.querySelector('input').value
  }

console.log( my_arry)

答案 1 :(得分:0)

尝试此代码

var my_arry = { "Description": "Actual Opening stock",
                     "Fri 05-Aug": "<input type='text' class='form-control' value='600'>",
                     "Mon 01-Aug": "<input type='text' class='form-control' value='200'>",
                     "Thu 04-Aug": "<input type='text' class='form-control' value='500'>",
                   }

var arr_new = {};

$.each( my_arry, function( key, value ) {
                if(key != "Description" ){ 
                        arr_new[key] = $(value).val();
                } else {
                        arr_new[key] = value;
                } });

console.log(arr_new)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>