如何在javascript或loadash中将每个数组元素转换为单个数组

时间:2021-09-25 13:41:55

Hi i am having an array like this, I want to make each Element as an array, i used chunk in lodash but no use. The

你好,我有一个像这样的数组,我想让每个元素成为一个数组,我在lodash中使用了chunk,但没有用。的

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

Result i am expecting is like this

我期待的结果是这样的。

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

can anybody Help Me on this

有人能帮我一下吗

4 个解决方案

#1


2  

if it is a onedimensional array, you can use the map function:

如果是一个一维数组,可以使用map函数:

var arr = ['Product 1', 'Product 2', 'Product 3', 'Product 4', 'Product 5', 'Product 6'];


var result = arr.map(function(el) {
  return [el];
});

console.log(result);

#2


1  

You can refer this also -

你也可以参考这个-

var arr1 = ['Product1', 'Product2', 'Product3', 'Product4'];

var arr2 = [];

for(var i=0;i<arr1.length;i++){
   var temparr = [];
   temparr.push(arr1[i]);
   arr2.push(temparr);
}
console.log(arr2);

Fiddle - https://jsfiddle.net/sajalsuraj/89vLty7k/

小提琴——https://jsfiddle.net/sajalsuraj/89vLty7k/

#3


0  

Check this out..

看看这个. .

 var x = [ 'Product 1', 'Product 2', 'Product 3', 'Product 4', 'Product 5', 'Product 6' ]
      var y = [];
      for(var i = 0;i<x.length;i++){
        var temp = [x[i]];
        y.push(temp);
      }
      console.log(y);

#4


0  

If you are using it in Node.js or is ES6 environment you could do:

如果在Node中使用它。或者是ES6环境你可以做:

let arr = products.map(p => [p]);

Example: http://www.es6fiddle.net/ips7zgh0/

例如:http://www.es6fiddle.net/ips7zgh0/

#1


2  

if it is a onedimensional array, you can use the map function:

如果是一个一维数组,可以使用map函数:

var arr = ['Product 1', 'Product 2', 'Product 3', 'Product 4', 'Product 5', 'Product 6'];


var result = arr.map(function(el) {
  return [el];
});

console.log(result);

#2


1  

You can refer this also -

你也可以参考这个-

var arr1 = ['Product1', 'Product2', 'Product3', 'Product4'];

var arr2 = [];

for(var i=0;i<arr1.length;i++){
   var temparr = [];
   temparr.push(arr1[i]);
   arr2.push(temparr);
}
console.log(arr2);

Fiddle - https://jsfiddle.net/sajalsuraj/89vLty7k/

小提琴——https://jsfiddle.net/sajalsuraj/89vLty7k/

#3


0  

Check this out..

看看这个. .

 var x = [ 'Product 1', 'Product 2', 'Product 3', 'Product 4', 'Product 5', 'Product 6' ]
      var y = [];
      for(var i = 0;i<x.length;i++){
        var temp = [x[i]];
        y.push(temp);
      }
      console.log(y);

#4


0  

If you are using it in Node.js or is ES6 environment you could do:

如果在Node中使用它。或者是ES6环境你可以做:

let arr = products.map(p => [p]);

Example: http://www.es6fiddle.net/ips7zgh0/

例如:http://www.es6fiddle.net/ips7zgh0/