Home > Enterprise >  map input field name to array of input field value as indexes
map input field name to array of input field value as indexes

Time:08-29

I have the following input fields:

<input name='223' type='number' class='form-control score' value='70'>
<input name='224' type='number' class='form-control score' value='65'>
<input name='225' type='number' class='form-control score' value='87'>

What I want is to make the 'name' attribute as index of each 'value' in JavaScript for ajax posting. i.e get values as single array, map the names as the array indexes

Something like this:
array (
[223] => 70
[224] => 65
[225] => 87
)

CodePudding user response:

You can use reduce method to accumulate the inputs values and names to an object with key as input name and value as input value.

const result = [...document.querySelectorAll('input[type="number"]')].reduce((acc, i) => ({...acc, [i.name]: i.value}), {})

console.log(result)
<input name='223' type='number' class='form-control score' value='70'>
<input name='224' type='number' class='form-control score' value='65'>
<input name='225' type='number' class='form-control score' value='87'>

It's a bad practice to use array data structure with keys as a random numbers, the array is designed to have sequence of keys starting with 0

let array = [];

// It's a bad practice to use random index as a key for an array.
// this will create a 222 item with undefined as a value and the item number 223 with 222
array["222"] = 222;

console.log(array)

Using Array this way causes a memory leak.

CodePudding user response:

You may want an array of objects with key: value corresponding to name and score attribute of each element. One way to achieve this is with array.map()

const inputs = Array.from(document.querySelectorAll(".score"))
const indexes = inputs.map(item => ({[item.name]: item.value}))
console.log(indexes)
<input name='223' type='number' class='form-control score' value='70'>
<input name='224' type='number' class='form-control score' value='65'>
<input name='225' type='number' class='form-control score' value='87'>

CodePudding user response:

You can achive this using array or object

If you use array for this it will create multiple empty values because the name in your html starts from 223

var res = []
document.querySelectorAll('.score').forEach(d=>{
res[d.name] = d.value
})
console.log(res[223]) // 70
console.log(res[224]) // 65
// The res value will looks like [,,,,,,,,,,,70,65,87]

You can achive the same thing with object also

var res1 = {}
document.querySelectorAll('.score').forEach(d=>{
res1[d.name] = d.value
})
console.log(res1[223]) // 70
console.log(res1[224]) // 65
// The sample res1 value looks like {'223':70,'224':65,'225':87} 

CodePudding user response:

Rather than an Array, I'd suggest using an Object as numeric indices on an Array will create an Array-entry at that index, leading to a very sparse, and mostly empty but very large, Array.

One approach is as below:

// helper utitilies, largely to reduce typing in larger projects;
// caching a reference to document:
const D = document,
  // an alias for querySelectorAll() that accepts an Element as
  // a context within which to search for the supplied selector,
  // defaulting to document:
  get = (sel, ctx = D) => ctx.querySelector(sel),
  // similar to the above, but an alias for querySelectorAll(),
  // and here we convert the NodeList returned from querySelectorAll()
  // into an Array in order to use Array methods:
  getAll = (sel, ctx = D) => [...ctx.querySelectorAll(sel)],
  // simple function to take a selector, retrieves the elements
  // matching that selector and then iterates over the Array of
  // Element Nodes:
  collate = (sel) => getAll(sel).map(
  // using an Arrow function along with destructuring assignment to
  // retrieve the 'name' and 'value' properties of the Element, and
  // passing those into the function body:
  ({
    name,
    value
  }) => {
    // here we return the Object formed from the name variable,
    // and supplying the value property of the Element as the
    // property-value:
    return {
      [name]: value
    }
  }),
  // calling the function on all <input> elements (adjust the selector
  // for more precise control):
  nameAndValues = collate('input'),
// this could also benefit from being converted into JSON:
  nameAndValuesJSON = JSON.stringify(nameAndValues);
  
  console.log(nameAndValues);
  console.log(nameAndValuesJSON);
<input name='223' type='number' class='form-control score' value='70'>
<input name='224' type='number' class='form-control score' value='65'>
<input name='225' type='number' class='form-control score' value='87'>

JS Fiddle demo.

References:

  • Related