0

I want to convert this string to array of objects.

Here is my String

var a = 'SG 925|AMD-MAA|19:15|21:40|SG 703|VNS-BOM|19:45|22:05';

I want to convert like this

[
{'name':'SG 925','place':'AMD-MAA','from':'19:15','to':'21:40'}
{'name':'SG 703','place':'VNS-BOM','from':'19:45','to':'22:05'}
]

Here is what i have tried so far

var a = 'SG 925|AMD-MAA|19:15|21:40|SG 703|VNS-BOM|19:45|22:05';
a = a.split("SG ");
a = a.filter(function(e){return e}); 
console.log(a);

Here is my Fiddle

How can i do this in javascript?

3
  • Do names always start with SG? Commented Jul 17, 2018 at 18:02
  • Yes it always starts with SG, so i thought of doing string split to make it array.. Commented Jul 17, 2018 at 18:04
  • Problem with that is you remove the SG when you split Commented Jul 17, 2018 at 18:10

3 Answers 3

2

If you have defined exaclty what the keys are gonna be like you could use something like this.

var a = 'SG 925|AMD-MAA|19:15|21:40|SG 703|VNS-BOM|19:45|22:05'
const arr = a.split('|')
const objArr = []

for (var i = 0; i < arr.length; i+=4) {
	objArr.push({
  	name: arr[i],
        place: arr[i+1],
        from: arr[i+2],
        to: arr[i+3]
  })
}

console.log(objArr)

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

Comments

0
var a = 'SG 925|AMD-MAA|19:15|21:40|SG 703|VNS-BOM|19:45|22:05';
a = a.split("|");
answer = [];
a.forEach(function(value, i) {
  if(i % 4 == 0) {
     answer.push({
       name: a[i],
       place: a[i + 1],
       from: a[i + 2],
       to: a[i + 3]
     })
  };
})
console.log(answer);

Comments

0

Try this. :)

function convert(str) {
  var strArr = str.split('|');
  var objArr = [];
  for(var i=0; i<strArr.length; i=i+4){
   objArr.push({
    'name':strArr[i],
    'place':strArr[i+1],
    'from':strArr[i+2],
    'to':strArr[i+3]
   })
  }
  return objArr;
}

console.log(convert('SG 925|AMD-MAA|19:15|21:40|SG 703|VNS-BOM|19:45|22:05'));

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.