0

I have a string of comma separated values. As below:

var myValues = "Ip1, Ip2, Ip3";

I want to convert this to a custom object. The result should be:

 {
  Input: 'Ip1',
  Output: 'Ip1_Updated'    
 },
 { 
  Input: 'Ip2',
  Output: 'Ip2_Updated'
 },
 { 
  Input: 'Ip3',
  Output: 'Ip3_Updated'
 }

What is the best way to approach this. Can I split on "," and then loop through the string and create custom array

2
  • 3
    why not try your idea (split on ",", then loop) first? Commented Mar 28, 2018 at 16:10
  • 2
    Can I split on "," and then loop through the string and create custom array. Yes, you can. Commented Mar 28, 2018 at 16:11

2 Answers 2

5

You can split an then use the function map

var myValues = "Ip1, Ip2, Ip3",
    result = myValues.split(",").map(s => ({ Input: s.trim(), Output: `${s.trim()}_Updated` }));
 
 console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0; }

Another alternative, is preparing the data and then convert to the desired structure:

var myValues = "Ip1, Ip2, Ip3",
    split = myValues.split(","),
    preparedData = split.map(str => str.trim()),
    result = preparedData.map(ip => ({ Input: ip, Output: `${ip}_Updated` }));
 
 console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Sign up to request clarification or add additional context in comments.

3 Comments

It'd be cleaner to use an additional map step to trim things: .split(',').map(x => trim...).map(...)
@georg two loops?
@Ele I have another question which is related to this mapping json. Would appreciate if you can look at this: stackoverflow.com/questions/49556448/…
2

You can use split() and map():

var myValues = "Ip1, Ip2, Ip3";
myValues = myValues.split(',').map(function(i){
  return {Input: i.trim(), Output: i.trim() + '_Updated'};
});

console.log(myValues);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.