Angular 5 - 如何构建具有多个键和值的对象
Angular 5 - How to build an object with several key's and values
我正在尝试构建一个将具有键及其值的对象:
const codeRed = this.orderInProgressCmsModel.orderStatusColorRed.split(",");
const codeGreen = this.orderInProgressCmsModel.orderStatusColorGreen.split(",");
const testObj = { colorName: "", colorCodes: []};
我正在执行以下操作以将信息添加到对象本身:
testObj.colorName = "red";
testObj.colorCodes = codeRed;
testObj.colorName = "green";
testObj.colorCodes = codeGreen;
虽然这样做只会将最后两个添加到我的对象中作为它的覆盖。
我的目的是尝试重构以下代码以避免使用太多 if,并尽可能使用更合乎逻辑的方法获得相同的结果:
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"}');
}
使 testObj 成为一个数组并将值推送到它,如下所示:
const testObj = [];
let itemToPush = {colorName: 'red', colorCodes: 'color-code'}
testObj.push(itemToPush);
好吧,在仔细考虑之后,我真正需要的是一个对象数组,所以我做了以下操作:
const testObj: Array<{ colorName: string, colorCodes: string[] }> = [
{ "colorName": "red", "colorCodes": codeRed },
{ "colorName": "green", "colorCodes": codeGreen },
{ "colorName": "black", "colorCodes": codeBlack }
];
这样我得到这个:
(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)
我正在尝试构建一个将具有键及其值的对象:
const codeRed = this.orderInProgressCmsModel.orderStatusColorRed.split(",");
const codeGreen = this.orderInProgressCmsModel.orderStatusColorGreen.split(",");
const testObj = { colorName: "", colorCodes: []};
我正在执行以下操作以将信息添加到对象本身:
testObj.colorName = "red";
testObj.colorCodes = codeRed;
testObj.colorName = "green";
testObj.colorCodes = codeGreen;
虽然这样做只会将最后两个添加到我的对象中作为它的覆盖。
我的目的是尝试重构以下代码以避免使用太多 if,并尽可能使用更合乎逻辑的方法获得相同的结果:
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"}');
}
使 testObj 成为一个数组并将值推送到它,如下所示:
const testObj = [];
let itemToPush = {colorName: 'red', colorCodes: 'color-code'}
testObj.push(itemToPush);
好吧,在仔细考虑之后,我真正需要的是一个对象数组,所以我做了以下操作:
const testObj: Array<{ colorName: string, colorCodes: string[] }> = [
{ "colorName": "red", "colorCodes": codeRed },
{ "colorName": "green", "colorCodes": codeGreen },
{ "colorName": "black", "colorCodes": codeBlack }
];
这样我得到这个:
(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)