-2

I got object array like this:

const matches = [
    {
        homeTeam: 'France',
        awayTeam: 'Croatia',
        score: '2:1',
        date: '18.01.2019'
    },

I need to add one more object "Points" to this array and initialize it to 0.

I expect to add this object and print it to console

cuman
  • 1
  • 4

4 Answers4

0

Try map method from array.prototype.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

matches.map(col => col.Points = 0)

You can use below if you need ES5 syntax means you're on web browser.

matches.map(function() {
  return col.Points = 0
})

The point of changes are using return statement to set value.

Seia
  • 48
  • 1
  • 6
0

let matches = [{
  homeTeam: 'France',
  awayTeam: 'Croatia',
  score: '2:1',
  date: '18.01.2019'
}]

let newArrayWithPoints = matches.map(o => ({ ...o,
  Points: 0
}))

console.log('newArrayWithPoints', newArrayWithPoints)

since its an array of objects you can create a new property by looping through it and return a new copy of array using array.map

i hope this will solve the issue

let newArrayWithPoints = matches.map(o => ({...o, Points: 0}))
Learner
  • 8,379
  • 7
  • 44
  • 82
0

If you want to add at the time of initialization use

const matches = [
{
    homeTeam: 'France',
    awayTeam: 'Croatia',
    score: '2:1',
    date: '18.01.2019'
},{ points: 0 }]

but if you want to add after initialization, don't make it constant variable and use push method .

0

Am I missing some complexity? - - simply target the object in the array and set the property.

let matches = [{
  homeTeam: 'France',
  awayTeam: 'Croatia',
  score: '2:1',
  date: '18.01.2019'
}]

matches[0].points = 0;


console.log(matches)
//[
//  {
//    "homeTeam": "France",
//    "awayTeam": "Croatia",
//    "score": "2:1",
//    "date": "18.01.2019",
//    "points": 0
//  }
//]

If there are multiple matches in the array - simply iterate over the array and do the same.

let matches = [
{
  homeTeam: 'France',
  awayTeam: 'Croatia',
  score: '2:1',
  date: '18.01.2019'
},{
  homeTeam: 'Italy',
  awayTeam: 'Germany',
  score: '2:0',
  date: '9.06.2019'
}]


matches.forEach(function(match){
  match.points = 0;
})


console.log(matches)
//[
//  {
//    "homeTeam": "France",
 //   "awayTeam": "Croatia",
//    "score": "2:1",
//    "date": "18.01.2019",
//    "points": 0
//  },
//  {
//    "homeTeam": "Italy",
//    "awayTeam": "Germany",
//    "score": "2:0",
//    "date": "9.06.2019",
//    "points": 0
//  }
]//
gavgrif
  • 15,194
  • 2
  • 25
  • 27