将JS对象转换为数组-duplicate- [英] Converting a JS object to an array -duplicate-

查看:117
本文介绍了将JS对象转换为数组-duplicate-的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道别人可能会问我这个问题.

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

我指的是这个关于stackoverflow的问题. Dogbert 已经正确给出了答案.此处 Dogbert 回答:

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);

输出:

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

我在输出console.log之后添加1行代码,以将数据传递到文本字段

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

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

我在文本字段中得到的值是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]] 

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

真的希望得到任何人的帮助!谢谢

Really hope from anyone help! thanks

推荐答案

如果我理解正确,您是否想将对象转换为字符串? 如果是这样,您可以这样做:

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

您的对象:

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]]

这篇关于将JS对象转换为数组-duplicate-的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆