【问题标题】:Convert an array into an array of arrays using javascript?使用javascript将数组转换为数组数组?
【发布时间】:2020-06-30 00:01:00
【问题描述】:

我想在 excel 文件上打印一些内容,并且该 excel 文件适用于数组数组的格式,所以我需要将数组转换为数组数组,如下所示:

['x','y','z'] to [['x'],['y'],['z']] 

我已经尝试使用 firestore 来存储这个并将其推送到阵列上

const query = async() => {
  const querySnapshot = await db.collection('collectionName').get();
  const data = []
  querysnapshot.forEach(doc => {
    const x = getIdentifier(doc)
    data.push(x)
  })
  console.log(data) //it gives an array like this ['x','y','z'] 
}
query();

【问题讨论】:

  • console .log (data .map (x => [x])) 应该是你所需要的。
  • 请正确格式化您的代码,这样便于其他人阅读。另外,如果您的问题是 ['x','y','z'] to [['x'],['y'],['z']],您为什么要添加有关 firebase 的信息?
  • 使用How to convert simple array into two-dimensional array (matrix) with Javascript 的任何答案并将“每个数组的元素数”设置为1。
  • 另请注意,您可以使用const data = querysnapshot .map (getIdentifier) 进行相当多的简化(假设querysnapshot 只是一个数组。)
  • @ScottSauyet 确实如此,我更喜欢看到querysnapshot.map((data) => getIdentifier(data))

标签: javascript arrays


【解决方案1】:

只需使用map:

const array = ['x','y','z'];
const array2 = array.map(value => [value]);

console.log(array2) // [['x'],['y'],['z']] 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-26
    • 2011-08-02
    • 1970-01-01
    • 1970-01-01
    • 2015-09-22
    • 2018-12-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多