JavaScript中的嵌套数组转换为字符串

4
我很困惑如何将嵌套的数组转换为字符串,但仍然有一个数组在字符串中,有人可以帮我吗?
输入: [["Jimmy", 30, ["Ford", "BMW", "Fiat"]], ["Fiona", 25, ["Ford", "BMW", "Fiat"]], ["Anny", 19, ["Ford", "BMW", "Fiat"]], ["Gabby", 27, ["Ford", "BMW", "Fiat"]], ["Kevin", 20, ["Ford", "BMW", "Fiat"]]] 期望输出:
"Jimmy,30,[Ford,BMW,Fiat]
   Fiona,25,[Ford,BMW,Fiat]
   Anny,19,[Ford,BMW,Fiat]
   Gabby,27,[Ford,BMW,Fiat]
   Kevin,20,[Ford,BMW,Fiat]"

谢谢


当您循环遍历外部数组时,请检查单个项是否为数组 - Array.isArray() - https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray - vabii
2
JSON.stringify 提供了一个非常接近的输出。 - trincot
7个回答

3
我们可以使用递归函数将任何数组中的所有内容存储到一个字符串中,然后从函数中返回该字符串。

function printArr(arr) {
let str = "";
  for (let item of arr) {
    if (Array.isArray(item)) str += printArr(item);
    else str += item + ", ";
  }
  return str;
}

console.log( 
printArr([
  ["Jimmy", 30, ["Ford", "BMW", "Fiat"]],
  ["Fiona", 25, ["Ford", "BMW", "Fiat"]],
  ["Anny", 19, ["Ford", "BMW", "Fiat"]],
  ["Gabby", 27, ["Ford", "BMW", "Fiat"]],
  ["Kevin", 20, ["Ford", "BMW", "Fiat"]]
]) 
);


1
你应该用","替换掉" ",并且需要在printArr(item)周围加上[ ... ]。 - Jonas Wilms
@JonasW。我发帖后意识到将 " " 改为 ",",但我不知道你所说的需要方括号 [...] 是什么意思? - zfrisch
Jimmy,30,[Ford,BMW,Fiat] <- ? 吉米,30岁,[福特,宝马,菲亚特] <- ? - Jonas Wilms
@JonasW。哦,我想我有点困惑。我以为OP是在暗示他们不想让数组仍然在字符串中? - zfrisch
@haha 你能澄清一下吗? - zfrisch
函数打印数组(arr){ let str = "["; for (let [i,v] of arr.entries()) { if (Array.isArray(v)) str += printArr(v); else str += v + (i < arr.length-1 ? ", " : ""); } return str+"]"; } - gabriel_agm

2
您可以使用嵌套的array#reduce方法。在内部数组中,检查是否为数组,并生成逗号分隔的数组,然后将结果附加到结果中。

var arr = [["Jimmy", 30, ["Ford", "BMW", "Fiat"]], ["Fiona", 25, ["Ford", "BMW", "Fiat"]], ["Anny", 19, ["Ford", "BMW", "Fiat"]], ["Gabby", 27, ["Ford", "BMW", "Fiat"]], ["Kevin", 20, ["Ford", "BMW", "Fiat"]]],
    result = arr.reduce((r, a) => {
      var arr = a.reduce((res,v) => { 
        var val = Array.isArray(v) ? `[${v.join(',')}]` : v;
        res.push(val);
        return res;
      }, []); 
      return r + arr.join(',') + '\n';
    }, '');
console.log(result);


1
有一个可能的解决方案...它只是将每个项目的第三个元素格式化为字符串,以便在末尾连接:
var data = [["Jimmy", 30, ["Ford", "BMW", "Fiat"]], ["Fiona", 25, ["Ford", "BMW", "Fiat"]], ["Anny", 19, ["Ford", "BMW", "Fiat"]], ["Gabby", 27, ["Ford", "BMW", "Fiat"]], ["Kevin", 20, ["Ford", "BMW", "Fiat"]]]
var dataAsString = data.map(function(d){ return [d[0], d[1],'[' + d[2].join(',') + ']']})
var output = dataAsString.join(',');

1

一个天真的解决方案是使用JSON.stringify,然后使用一点replace来使其格式更好:

let result = JSON.stringify([["Jimmy", 30, ["Ford", "BMW", "Fiat"]], ["Fiona", 25, ["Ford", "BMW", "Fiat"]], ["Anny", 19, ["Ford", "BMW", "Fiat"]], ["Gabby", 27, ["Ford", "BMW", "Fiat"]], ["Kevin", 20, ["Ford", "BMW", "Fiat"]]])
 .replace(/(\]\]\,)\[/g, "]\n") // Adding new lines and removing starting [
 .replace(/(\[\[|\]\]|\")/g,""); // removing junk
console.log(result);

干净的解决方案是根据收到的对象自己构建字符串。

0

这里是一个处理它的小递归函数:

const input = [["Jimmy", 30, ["Ford", "BMW", "Fiat"]], ["Fiona", 25, ["Ford", "BMW", "Fiat"]], ["Anny", 19, ["Ford", "BMW", "Fiat"]], ["Gabby", 27, ["Ford", "BMW", "Fiat"]], ["Kevin", 20, ["Ford", "BMW", "Fiat"]]];

function toString(input, level) {
    // input is not an array, therefore just return the input itself
    if (!Array.isArray(input)) {
        return input + ",";
    } else {
        if (Array.isArray(input) && level < 2) {
            // first two levels of arrays should be broken down
            let text = "";
            input.forEach(part => text += toString(part, level+1));
            text += "\n";
            return text;
        } else {
                // third level of arrays should just be printed, but without quotes
                let text = JSON.stringify(input);
                while (text.indexOf("\"") > -1) {
                    text = text.replace("\"", "");
                }
                return text;
        }
    }
}

const result = toString(input, 0)
console.log(result);


0

简单的 forEach 解决方案。 使用 JS 的内部 Array.toString() 功能来处理最内层的数组。

var arr=[["Jimmy", 30, ["Ford", "BMW", "Fiat"]], ["Fiona", 25, ["Ford", "BMW", "Fiat"]], ["Anny", 19, ["Ford", "BMW", "Fiat"]], ["Gabby", 27, ["Ford", "BMW", "Fiat"]], ["Kevin", 20, ["Ford", "BMW", "Fiat"]]]

var str='';

arr.forEach(function(el) {str += el[0] + ', ' + el[1] + ', [' + el[2] + '] '});

console.log(str);


-1
你可以使用 Lodash 来实现这个功能。

var data = [["Jimmy", 30, ["Ford", "BMW", "Fiat"]], ["Fiona", 25, ["Ford", "BMW", "Fiat"]], ["Anny", 19, ["Ford", "BMW", "Fiat"]], ["Gabby", 27, ["Ford", "BMW", "Fiat"]], ["Kevin", 20, ["Ford", "BMW", "Fiat"]]]

var flattenedData = _.flattenDeep(data);

var stringifiedData = _.toString(flattenedData)

console.log(stringifiedData);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>


3
你可以使用纯JS而不导入其他额外的重型库。 - Antony
@Antony 为什么会有 -1?这不是一个可能的答案吗? - arunmmanoharan
1
除了你在一个纯JS问题中引入了完全不需要的库之外,结果根本没有格式化,也没有回答这个问题。 - Antony

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接