Home > Net >  Why when I set the value of an hidden input to a value of an array of objects it makes every item in
Why when I set the value of an hidden input to a value of an array of objects it makes every item in

Time:03-08

I have this code:

for(let i =0; i < upbtn.length; i  ){
  upbtn[i].addEventListener('click', function(){
    let whichTopic = i
    if(whichTopic == 0){
      return true
    }
    else{
      let arr = coursenewtopics.value
      arr = JSON.parse(arr)
      arraymove(arr, i, i-1)
      coursenewtopics.value = arr
      console.log(arr)
      console.log(coursenewtopics.value)
      //changeordertopicsform.submit()
    }
  })
}

I am trying to sort an array from an hidden input then set the value of the hidden input to the sorted array, I console logged the results from the sorted array(arr)

[
    {
        "type": "text",
        "name": "",
        "text": ""
    },
    {
        "type": "text",
        "name": "2",
        "text": ""
    },
    {
        "type": "text",
        "name": "1",
        "text": ""
    },
    {
        "type": "text",
        "name": "3",
        "text": ""
    },
    {
        "type": "text",
        "name": "4",
        "text": ""
    }
]

and the results are what I want, however when after I put this value I just logged of arr to the hidden input, then console log the value of the hidden input becomes:

[object Object],[object Object],[object Object],[object Object],[object Object]

why does JavaScript act this? how do I fix this an put the values into the hidden input without making them go [object Object]? I need them for a form later on.

Thanks!

CodePudding user response:

so your problem is 'How to display an array of object literally'.

you can try JSON.stringify(arr, null, ' ')

  • Related