Converting a JS object to an array -duplicate-

2019-09-14 22:30发布

问题:

I know that my question might be questioned before by others.

I am referring to this question on stackoverflow. Dogbert already give the answered correctly. here Dogbert answered:

var myObj = {
1: [1, 2, 3],
2: [4, 5, 6]
};

var array = $.map(myObj, function(value, index) {
  return [value];
});

console.log(array);

output:

[[1, 2, 3], [4, 5, 6]]

I add 1 line code after output console.log which to pass the data to text field

$('#assign').val(array);

I got the value array in my text field like this:

1,2,3,4,5,6

Is there any way to reformat the data on text field become like this:

[[1,2,3],[4,5,6]] 

or

[{1,2,3},{4,5,6}]

Really hope from anyone help! thanks

回答1:

If I understand right, you want to turn your object into a string? If so, you could do this :

Your object :

var myObj = {
1: ["a", "3", "h"],
2: ["r", "y", "s"]
};

Turn your object to an array of strings

var array = jQuery.map(myObj, function(value) {
  return "[" + value + "]";
});

Start your string, fill it with your values

var myString = "[";
array.forEach(function(value){myString += value + ","}); 

Then remove the last coma and put in your last bracket :

myString = myString.substring(0,myString.length-1) + "]";

Now, if you should have your string with the required format

alert(myString); //[[a,3,h],[r,y,s]]