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

Issue

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"}'); 
}

Solution

Okay after thinking it through a bit more what I actually needed was an Array of Objects, so I did the following:

const testObj: Array<{ colorName: string, colorCodes: string[] }> = [
      { "colorName": "red", "colorCodes": codeRed },
      { "colorName": "green", "colorCodes": codeGreen },
      { "colorName": "black", "colorCodes": codeBlack }
    ];

This way I get this:

(3) [{…}, {…}, {…}]
0:
    colorName: "red"
    colorCodes: (3) ["2", "3", "8"]
__proto__: Object
1:
    colorName: "green"
    colorCodes: (3) ["0", "1", "7"]
__proto__: Object
2:
    colorName: "black"
    colorCodes: (4) ["4", "5", "6", "9"]
__proto__: Object
length: 3
__proto__: Array(0)

Answered By – MONZTAAA

Answer Checked By – Timothy Miller (AngularFixing Admin)

Leave a Reply

Your email address will not be published.