Home > Back-end >  js make object from string
js make object from string

Time:09-01

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

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

CodePudding user response:

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}]

CodePudding user response:

i have to make a object

But you then claim that your expected output is an array, not an object:

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

In that case, make an array and then .push() to that array within the loop:

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

CodePudding user response:

This should work fine:

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

var results = [];
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]);
        results.push(result);
  });
  return results;
})();
console.log(results)

The problem with your code was that you successfully splitted the string and converted it to the object but as you are expecting the result to be in the array you were not storing the object rather were rewriting the same object time and again.

  • Related