jeudi 30 janvier 2020

Angular 5 - How to build an object with several key's and values

Im trying to build an object that is going to have a key and its values:

const codeRed = this.orderInProgressCmsModel.orderStatusColorRed.split(",");
const codeGreen = this.orderInProgressCmsModel.orderStatusColorGreen.split(",");

const testObj = { colorName: "", colorCodes: []};

Im doing the following to add the information to the object itself:

testObj.colorName = "red";
testObj.colorCodes = codeRed;
testObj.colorName = "green";
testObj.colorCodes = codeGreen;

Doing it this way though will only add the last two into my object as its overwriting.

The purpose is that im trying to refactor the following code to avoid using so many if's and trying to get the same result with a more logical approach if possible:

if(codeRed.some(s => s.includes(code))){
  this.orderStatusColor = JSON.parse('{"color": "red"}');
}

if (codeGreen.some(s => s.includes(code))){
  this.orderStatusColor = JSON.parse('{"color": "green"}');
}

if (codeBlack.some(s => s.includes(code))){
  this.orderStatusColor = JSON.parse('{"color": "black"}'); 
}

Aucun commentaire:

Enregistrer un commentaire