-3

I have html code which looks like below :

<input type="text" name="fruits[apple]" value="true">
<input type="text" name="fruits[orange]" value="false">
<input type="text" name="fruits[mango]" value="true">

How do I select all the fruits and get their respective values? I'm looking for an object like

{
  "apple": true,
  "orange": false,
  "mango": true
}
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
Tintin
  • 475
  • 1
  • 5
  • 16
  • Related: https://stackoverflow.com/questions/33615334/jquery-finding-partial-class-name/33615377#33615377 – Taplar May 30 '19 at 21:02

1 Answers1

3

You can select elements which start with fruits[, and map to their values:

const vals = $('[name^="fruits["]')
  .map((_, input) => input.value)
  .get();
console.log(vals);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="fruits[apple]" value="true">
<input type="text" name="fruits[orange]" value="false">
<input type="text" name="fruits[mango]" value="true">

Keep in mind that the .value of inputs are strings - if you need booleans instead, you'll have to do so more explicitly:

const vals = $('[name^="fruits["]')
  .map((_, input) => input.value === 'true')
  .get();
console.log(vals);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="fruits[apple]" value="true">
<input type="text" name="fruits[orange]" value="false">
<input type="text" name="fruits[mango]" value="true">

If you need the unique part of the name as well, then reduce into an object of key-value pairs (and may as well drop the jQuery if using reduce):

const vals = [...document.querySelectorAll('[name^="fruits["]')]
  .reduce((a, { name, value }) => {
    const key = name.match(/[^[]+(?=\])/)[0];
    a[key] = value === 'true';
    return a;
  }, {});
console.log(vals);
<input type="text" name="fruits[apple]" value="true">
<input type="text" name="fruits[orange]" value="false">
<input type="text" name="fruits[mango]" value="true">
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320