Miguel Moura
Miguel Moura

Reputation: 39404

Change value of property of all objects except in one

I have an array of the candidacies:

candidacies = service.getCandidacies();

where each candidacy is an object such as:

{ id: 1, isHired: true }, 
{ id: 4, isHired: false }, 
{ id: 8, isHired: false }

I need to set all candidacies in the list with isHired = false and the one with id = 4 as isHired = true. I have more objects in the array. These are one example.

I tried to use the map function but not sure how to use it or if is even possible:

  candidacies = candidacies.map(function(x) {

  });

But I am not sure how or if is even possible ...

Upvotes: 2

Views: 1127

Answers (4)

Alberto Trindade Tavares
Alberto Trindade Tavares

Reputation: 10366

You can use forEach for this (as you are changing the variable anyway):

var candidacies = [{ id: 1, isHired: true }, 
                   { id: 4, isHired: false }, 
                   { id: 8, isHired: false }];

candidacies.forEach(function(candidacy) {
  candidacy.isHired = (candidacy.id === 4);
});

console.log(candidacies);

If you really want to use map (which is good if you assign the result to another variable), you can do this:

var candidacies = [{ id: 1, isHired: true }, 
                   { id: 4, isHired: false }, 
                   { id: 8, isHired: false }];

var newCandidacies = candidacies.map(function(candidacy) {
  return Object.assign({}, candidacy, { isHired: (candidacy.id === 4) });
});

console.log(newCandidacies);

Upvotes: 0

ramongr
ramongr

Reputation: 55

This looks like a question a student would ask, if that's the case we're not here to solve your homework for you. The map function iterates through an array and applies whatever function() you define. Either way you can run some console.log(x) to see how it might work. Best of luck.

Upvotes: -2

RickTakes
RickTakes

Reputation: 1197

Assuming your objects are in an array as such:

candidacies = [
  { id: 1, isHired: true }, 
  { id: 4, isHired: false }, 
  { id: 8, isHired: false }
]

Then the map would look like:

candidacies = candidacies.map(function(candidate, index) {
  candidate.isHired = candidate.id === 4; 
  return candidate;
})

Upvotes: 2

Paul
Paul

Reputation: 36329

Using your own stub, the easiest approach is to just add a logical test:

candidacies = candidacies.map(function(x) {
    x.isHired = x.id === 4;
    return x;
});

Upvotes: 1

Related Questions