-1

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}]
2
  • You are overwriting the properties of result on every iteration, leaving you with the value of the last iteration. Commented Aug 31, 2022 at 14:10
  • "i have to make a object" - And you are successfully making an object. But then you claim that the output you need is an array, not an object. Shouldn't you be making an array then? Commented Aug 31, 2022 at 14:12

3 Answers 3

1

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}]
Sign up to request clarification or add additional context in comments.

Comments

0

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;

Comments

0

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.

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.