【发布时间】:2023-03-05 20:57:01
【问题描述】:
我又一次被困在向深度嵌套的数组中添加属性。我所拥有的是:
myArray = [
{
"id": "123",
"station": {
"id": 5,
"name": "Teststation"
},
"values": [
{
"id": "way",
"values": [ 339, 340, 341 ]
},
{
"id": "time",
"values": [ 1, 2, 3 ]
},
{
"name": "element_1",
"type": "line",
"result": "nok"
},
{
"name": "element_2",
"type": "rect",
"result": "nok"
},
{
"name": "element_3",
"type": "line",
"result": "ok"
}
]
}
]
myArray 可能包含更多具有与此相同结构的对象。所以我必须循环它们。我想要实现的是: 我想向拥有名为“line”或“rect”的属性的对象添加属性并且 新属性取决于结果的值
所以新的结果应该是这样的:
myArray = [
{
"id": "123",
"station": {
"id": 5,
"name": "Teststation"
},
"values": [
{
"id": "way",
"values": [ 339, 340, 341 ]
},
{
"id": "time",
"values": [ 1, 2, 3 ]
},
{
"name": "element_1",
"type": "line",
"result": "nok"
"line": { color: 'red' }
},
{
"name": "element_2",
"type": "rect",
"result": "nok",
"opacity": 0.2,
"line": { color: 'gray', width: 0 },
"fillcolor": 'green'
},
{
"name": "element_3",
"type": "line",
"result": "ok"
"line": { color: 'green' }
}
]
}
]
到目前为止,我尝试的方法似乎都有效,直到我意识到:它返回一个数组,其中包含一个包含该对象的数组。我不明白它为什么这样做以及如何只获取一个包含对象的数组。谁能帮我解决这个问题?
addColor(myArray) {
return myArray.map(obj => {
for (const prop in obj) {
if (obj.hasOwnProperty(prop) && Array.isArray(obj[prop])) {
for (const item in obj[prop]) {
if (obj[prop][item].hasOwnProperty('result') && (obj[prop][item].type === 'line')) {
obj[prop][item].result === 'nok' ? obj[prop][item].line = { color: 'red' } : obj[prop][item].line = { color: 'green' };
} else if (obj[prop][item].hasOwnProperty('result') && (obj[prop][item].type === 'rect')) {
obj[prop][item].opacity = 0.2;
obj[prop][item].line = { color: 'gray', width: 0 };
obj[prop][item].result === 'nok' ? (obj[prop][item].fillcolor = 'red') : (obj[prop][item].fillcolor = 'green');
}
}
}
}
console.log('myArray out', myArray);
// It doesn't return anything so far so I added
return myArray
// But then I do get [[{}]]
});
}
【问题讨论】:
-
我已经尝试了代码,我得到了一个数组。控制台响应中是否有省略号 (
...)?如果是这样,请尝试扩展它。
标签: javascript arrays object nested