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

125 Views Asked by At

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

There are 2 best solutions below

0
Victor York On BEST ANSWER

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)
0
Bodhi On

Make testObj an array and push the values to it like below:

const testObj = [];
let itemToPush = {colorName: 'red', colorCodes: 'color-code'}

testObj.push(itemToPush);