Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

js make object from string

i have to make a object from array then i can work with it letter.
i am trying this code it work’s but output getting only last one

let datas = "team1 1, team2 2, team3 3";

let teamdata = datas.split(" ");

var myObj = (function () {
  var result = { Tname: null, count: null };
  datas.split(/\s*\,\s*/).forEach(function (el) {
    var parts = el.split(/\s* \s*/);
    result.Tname = parts[0];
    result.count = parseInt(parts[1]);
  });
  return result;
})();

console.log(myObj);

output getting { Tname: 'team3', count: 3 }

need output

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[{name: "team1", count: 1},
{name: "team2", count: 2},
{name: "team3", count: 3}]

>Solution :

Simply, You could do it with
String.split() and Array.map()

let datas = "team1 1, team2 2, team3 3";
let teamdata = datas.split(", "); // ['team1 1', 'team2 2', 'team3 3']
let result = teamdata.map(team=>({team:team.split(/\s+/)[0],count:+team.split(/\s+/)[1]}))
console.log(result);

expected output:

[{name: "team1", count: 1},
{name: "team2", count: 2},
{name: "team3", count: 3}]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading