Rey Norbert Besmonte
Rey Norbert Besmonte

Reputation: 791

Javascript populate array with IF statement

Is there a way to populate an array with if condition inside?

example

cars = [
  {id:1,color:'red'},
  {id:2,color:'blue'},
  {id:3,color:'blue'}
]

I need to create a new array that will get the value of ID and a new field which is type.

if color = red, type = 1, else type = 0.

I tried this one but it will not work for javascript.

var newArray = [
   for(var car in cars){
       newId: car.id,
       if(car.color == 'red'){
          type: '1',
       else
          type: '0'
   }
]

the return value should be

newArray = [
       {newId:1,type:'1'},
       {newId:2,type:'0'},
       {newId:3,type:'0'}
]

Help please

Upvotes: 1

Views: 1755

Answers (5)

Phil
Phil

Reputation: 164899

You can easily map your original array to a new one

const cars = [{"id":1,"color":"red"},{"id":2,"color":"blue"},{"id":3,"color":"blue"}]

const newArray = cars.map(car => ({
  newId: car.id,
  type: car.color === 'red' ? '1' : '0'
}))

console.info(newArray)


If you need to support IE, this will work in v9+

var newArray = cars.map(function(car) {
  return {
    newId: car.id,
    type: car.color === 'red' ? '1' : '0'
  }
})

Versions of IE prior to 9 do not support Array.prototype.map. See this pollyfill if you need to support those.

Upvotes: 4

binariedMe
binariedMe

Reputation: 4329

Given array is wrong, If your array looks like this :

cars =[
  {id:1,color:"red"},
  {id:2,color:"blue"},
  {id:3,color:"blue"}
];

then you should do this :

var newArray = cars.map((car) => { let type; if(car.color === "blue") type = 1; else type = 0; return { id: car.id, color: car.color, type }})

Upvotes: 1

YCotov
YCotov

Reputation: 92

Try this instead your code:

     var newArray = [];
      for(var car in cars){
         if(car.color == 'red'){
             newArray.push({newId: car.id,type: '1'});
           } else {
              newArray.push({newId: car.id,type: '0'});
           }
       }

Upvotes: 0

Sholeman
Sholeman

Reputation: 1

That's what the Array Map function is for, You can create from another array.

However, your array is wrong and it has been corrected in the code below:

cars =[
    {id:1,color:'red'},
    {id:2,color:'blue'},
    {id:3,color:'blue'}
]
newCarArray=cars.map(function(car){
    if(car.color =='red'){
         return {newId:car.id, type:1}
    }
     return {newId:car.id, type:0}
})
console.log (newCarArray)

Upvotes: 0

GullDe
GullDe

Reputation: 390

I believe this is what you are looking for:

var newArray = [];
for(var car in cars) {
    var obj = {newId: car.id};
    if(car.color === 'red') {
        obj['type'] = '1';
    } else {
        obj['type'] = '0';
    }
    newArray.push(obj);
}

Upvotes: 1

Related Questions