nested array to string javascript - Stack Overflow

I am confused on how to convert a nested array into a string but there is still array inside a string,

I am confused on how to convert a nested array into a string but there is still array inside a string, can somebody help me?

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

expected output :

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

thank you

I am confused on how to convert a nested array into a string but there is still array inside a string, can somebody help me?

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

expected output :

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

thank you

Share Improve this question asked Jan 16, 2018 at 17:54 hahahaha 411 gold badge1 silver badge2 bronze badges 2
  • when you are looping through outer array, check if individual item is an array - Array.isArray() - developer.mozilla/en-US/docs/Web/JavaScript/Reference/… – vabii Commented Jan 16, 2018 at 17:57
  • 2 JSON.stringify provides an output that es very close. – trincot Commented Jan 16, 2018 at 18:06
Add a ment  | 

7 Answers 7

Reset to default 3

We can just use a recursive function to store anything and everything within any array in a string and then return the string from the function.

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

You can use nested array#reduce. Inside the inner array, check for array and generate ma-separated array and appended the result in the result.

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

There is a posible solution... it just formats the third element of each item as string so it can be joined at the end:

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(',');

A naive solution would be to use JSON.stringify then use a bit of replace to format it a bit better:

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

The clean solution would be to build the string yourself based on the objects you receive

Here is a small recursive function that handles it:

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

Simple forEach solution. Uses JS internal Array.toString() functionality for the inner-most array..

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

You can use lodash to achieve this.

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./ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1743669171a4487489.html

相关推荐

  • nested array to string javascript - Stack Overflow

    I am confused on how to convert a nested array into a string but there is still array inside a string,

    1天前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信