sai
sai

Reputation: 55

How to convert string into two properties inside an array?

Here I am doing to convert the array into required format. output of parsedValues is ["abcdefgh(4034343), Mikhail(900002)"] and Iam trying to convert it as ["abcdefgh(4034343)","Mikhail(900002)"]

How can I convert ["abcdefgh(4034343), Mikhail(900002)"] to ["abcdefgh(4034343)","Mikhail(900002)"] ?

private transformUser(userIdsString: any): string[] {
  const parsedUserIdsArray = userIdsString;
  console.log(parsedUserIdsArray);
  const parsedValues = parsedUserIdsArray[4].userids;
  console.log(parsedValues);
  const splitValues = parsedValues.split(',');
  console.log(splitValues);
  const trimmedValues = splitValues.map(str => str.trim());
  console.log(trimmedValues);
  return trimmedValues;
}

The console.log(trimmedValues) is 

(2) ["["abcdefgh(4034343)", "Mikhail(900002)"]"]
0: "["abcdefgh(4034343)"
1: "Mikhail(900002)"]"
length: 2
__proto__: Array(0)

Expected is : (2) ["abcdefgh(4034343)", "Mikhail(900002)"] 0: "abcdefgh(4034343)" 1: "Mikhail(900002)" length: 2 proto: Array(0)

Upvotes: 0

Views: 104

Answers (3)

YTScorpion
YTScorpion

Reputation: 31

const trimmedValues = parsedValues[0].split(', ');

Upvotes: 0

sminutoli
sminutoli

Reputation: 841

You can use split on the string, to get an array from a separator (, in this case). If you have only one joined string, you can do...

["abcdefgh(4034343), Mikhail(900002), Someone(12934)"][0].split(', ')

To obtain a new array.

If the original array has multiple strings, you'll need to join all the arrays...

["abcdefgh(4034343), Mikhail(900002)", "Someone(12934)"]
.map(item => item.split(', '))
.reduce( (acc, item) => [...acc, ...item], [])

Upvotes: 1

front_end_dev
front_end_dev

Reputation: 2056

Try this

var input = ["abcdefgh(4034343), Mikhail(900002)"]

input.reduce(function(o,i){
    var values = i.split(',');
    if(values.length > 0){
        o = o.concat(values);
    }return o;},[]);

Output - ["abcdefgh(4034343)", " Mikhail(900002)"]

Upvotes: 0

Related Questions