-1

I am using map JavaScript function to return an object. row.id throws error . I want to create id as key for every iteration in array.

<input value="3" id="first" class="pdate">
<input value="5" id="second" class="pdate">
<input value="2" id="third" class="pdate">
    if(document.querySelectorAll('.pdate')){
        let update = [...document.querySelectorAll('.pdate')].map(row => {
            return {
                row.id : row.value
            }
        })
    }
Akhi21
  • 219
  • 4
  • 16

2 Answers2

2

You can use Object.fromEntries to convert an array of key-value pairs to an object.

let update = Object.fromEntries([...document.querySelectorAll('.pdate')]
   .map(row => [row.id, row.value]));
console.log(update);
<input value="3" id="first" class="pdate">
<input value="5" id="second" class="pdate">
<input value="2" id="third" class="pdate">
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
1

Since you want to generate an object from the list of rows, use .reduce:

const update = [...document.querySelectorAll('.pdate')].reduce((acc,row) => {
  acc[row.id] = row.value;
  return acc;
}, {})

console.log(update);
<input value="3" id="first" class="pdate">
<input value="5" id="second" class="pdate">
<input value="2" id="third" class="pdate">
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48