0

Hi there i have this starting array:

names = [ '1A', '1B', '1C', '1D', '1E'];

which I need for later on in my application to see who's turn it is. I need to be able to store some values in a different kind of array like so:

scores = [
  {
    id: "1A",
    endScores: {}
  },
  {
    id: "1B",
    endScores: {}
  },
  {
    id: "1C",
    endScores: {}
  },
  {
    id: "1D",
    endScores: {}
  },
  {
    id: "1E",
    endScores: {}
  }
];

How is it possible to get from my first array to the second array? The first array can also change in its size there can be more or less names in there... Hope there is a possible way. PS: I'm using Angular 2.

2
  • 1
    Have a look at map Commented Dec 28, 2018 at 13:54
  • @AlekseyL.could u pls be a bit more specific as im new to javascript and these arrays are blowing my mind appart :( Commented Dec 28, 2018 at 13:56

3 Answers 3

2

This is how you can map your names array into desired collection.

const names = [ '1A', '1B', '1C', '1D', '1E'];

const transformToScores = names => names.map(id => ({id, endScores: {}}))

const scores = transformToScores(names)

console.log(scores)

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

5 Comments

will this then edit names? or will names stay like the original form?
@ArcherMark what do you mean? names are mapped to id property in the second collection without any transformation.
will the array of names stay in the format it was original or will that array be changed? i see that with youre code u are also creating a new array called scores. _transformToScores = names => _ this line is what is confusing me where my brain is saying that the names array is getting changed. But since i am new i could be completely wrong ...
@ArcherMark no, it stays the same. There's no mutability here. map method always returns new array.
@ArcherMark if this answers your question please mark this answer as correct. Thanks.
1

Using the map method it's pretty easy:

const names = [ '1A', '1B', '1C', '1D', '1E'];

const scores = names.map(name => {
  let item = {
    id: name,
    endScores: {}
  }
  return item;
})

console.log(scores);

Comments

0

var names = [ '1A', '1B', '1C', '1D', '1E'];

const newnames=names.map(Id=>Object.assign({},{
    id: Id,
    endScores: {}
    }
    ))
console.log(newnames)

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.