0

var a = $('.opti').map(function() {
    return $(this).attr('value');
}).toArray();

var b = $('.opti').map(function() {
    return $(this).attr('vid');
}).toArray();


console.log(a, b);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" class="opti" value="337" vid="231">

Output

["337"] ["231"]

Question: Above code is return the data in separate array, but what I want is put them into one array, for example it will be one array to store is 2 value, result will be ["337","231"].

2
  • 1
    What if there are multiple instances of .opti? Do you want to store them in an array of arrays (a 2D array containing elements with pairs of data), or a 1D array? Commented Aug 9, 2017 at 10:36
  • i think 2d array will be better Commented Aug 9, 2017 at 10:39

3 Answers 3

2

You can return array of both value and vid property using one map() method.

var attr = $(".opti").map(function() {
  return [$(this).val(), $(this).attr('vid')]
}).get();

console.log(attr)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" class="opti" value="337" vid="231">

To get 2D array for multiple input elements you can return [[$(this).val(), $(this).attr('vid')]] DEMO as suggested by @Terry

Sign up to request clarification or add additional context in comments.

1 Comment

If OP wants a 2D array (for situations where multiple elements matches the selector), you should return a nested array: [[$(this).val(), $(this).attr('vid')]]
1

Here is a solution for multiple instances of "opti" elements

var result = [];
$(".opti").each(function () {
  result.push([$(this).val(), $(this).attr("vid")]);
});
console.log(result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" class="opti" value="337" vid="231">
<input type="hidden" class="opti" value="336" vid="233">
<input type="hidden" class="opti" value="335" vid="232">

Comments

0

Use the .push methon and you can use many arguments, and .apply to pass all the elementos of the second array.

a.push.apply(a, b)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.