Home > Net >  How to convert string of Arrays into an Array?
How to convert string of Arrays into an Array?

Time:09-29

I want this "size": "[6],[8],[10],[12],[14],[16],[18]", to Look like this [6,8,10,12,14,16,18]
When I'm outputting a product.size it is coming like, Size - [6],[8],[10],[12],[14],[16],[18] .
But i want it like this, Size - 6 8 10 12 14 16 18 . product is an object which has many "key":"values" and "size": "[6],[8],[10],[12],[14],[16],[18]" is one of them. I have already tried JSON.parse(product.size) You can see in the image in the details of the card where it is showing size

CodePudding user response:

use a regex to capture the numeric strings from your object's value then convert them to numbers

let obj = {
    "size": "[6],[8],[10],[12],[14],[16],[18]"
}

let result = obj.size.match(/\d /g)
                     .map(e => parseInt(e))
                     
console.log(result)

CodePudding user response:

You've to flatten this array.

var size = [[6],[8],[10],[12],[14],[16],[18]];
var sizeArray = [].concat.apply([], size);

console.log(sizeArray);

UPDATE:

it would be good if you convert your string into array first like:

 var strArray = "[2],[4]"
    const arrayFromString = JSON.parse(`[${strArray}]`);
    var sizeArray = [].concat.apply([], arrayFromString);
    
    console.log(sizeArray);

CodePudding user response:

From the above comment ...

"The JSON.parse approach already points in the right direction. But in order to not fail with parsing a wrong JSON syntax one needs to replace all occurrences of ],[ within the string value with just , ... JSON.parse(product.size.replace((/\]\s*,\s*\[/g), ', '))".

The replace method also consumes regular expressions which in case of the OP should look like this ... /\]\s*,\s*\[/g ... and reads like that ...

  • match a closing bracket ... \] (needs to be escaped)
  • match an optional whitespace(-sequence) ... \s*
  • match a comma character ... ,
  • match an optional whitespace(-sequence) ... \s*
  • match an opening bracket ... \[ (needs to be escaped)
  • / ... /g the entire pattern has to match globally (matches every occurrence)

const product = { size: '[6],[8],[10],[12],[14],[16],[18]' };

console.log(
  JSON.parse(
    product.size.replace((/\]\s*,\s*\[/g), ', ')
  )
);
.as-console-wrapper { min-height: 100%!important; top: 0; }

Edit

"@PeterSeliger it worked like this Size - [ 6, 8, 10, 12, 14, 16, 18 ] thanks.. but I don't want even brackets and comma. I want Size - 6 8 10 12 14 16 18 . – Shahab Dad Khan"

In this case, one just needs to join all the items of the parsed array ...

const product = { size: '[6],[8],[10],[12],[14],[16],[18]' };

console.log(
  JSON.parse(
    product.size.replace((/\]\s*,\s*\[/g), ', ')
  ).join(' ')
);
.as-console-wrapper { min-height: 100%!important; top: 0; }

... or one builds upon Alan Omar's idea of matching all digit characters ...

const product = { size: '[6],[8],[10],[12],[14],[16],[18]' };

console.log(
  product.size.match(/\d /g).join(' ')
);
.as-console-wrapper { min-height: 100%!important; top: 0; }

CodePudding user response:

So it is as simple as using replaceAll with JSON.parse:

let str = "[6],[8],[10],[12],[14],[16],[18]";
//JSON.parse(str.replaceAll('],[', ','));
let arr = JSON.parse(str.replace((/\]\s?,\s?\[/g), ','));
console.log(arr);
// [6, 8, 10, 12, 14, 16, 18]

Thanks peter seliger for his note about the case where there are additional whitespaces somewhere in between ],[. for that case use regular expression with \s which means space and ? mean if there is space or not. and flag /g/ to replace all this matched with a comma ,.

CodePudding user response:

I am not sure why you want to make like this but you can follow this.

let data = {
    "size": "[6],[8],[10],[12],[14],[16],[18]"
}
let string = "[" data.size "]"
console.log(JSON.parse(string).join(',')) // will output "6,8,10,12,14,16,18"
console.log("[" JSON.parse(string).join(',') "]") // will output " [6,8,10,12,14,16,18]"


CodePudding user response:

Traverse once:

let size = "[6],[8],[10],[12],[14],[16],[18]";

let numArray=[];
let temp='';
for (let i=0;i<size.length;i  ) {
  let c = size[i];
  if (c===',' || i===size.length-1) {
    if (temp) {
      numArray.push(parseInt(temp));
      temp = '';
    }
  } else if (parseInt(c) || c==='0') {
    temp =c;
  }
}

console.log(numArray);

O(n)

CodePudding user response:

 var strArray = "[2],[4]";
 const arrayFromString = JSON.parse(`[${strArray}]`);
 var sizeArray = [].concat.apply([], arrayFromString);
 console.log(sizeArray);

  • Related