我有一个结构化的有效负载,如下例所示:
var payload = [
{
"firstService-2xx": 0.1,
"firstService-4xx": 0,
"firstService-5xx": 1.2,
"secondService-2xx": 5.4,
"secondService-4xx": 1,
"secondService-5xx": 0.2
},
{
"firstService-2xx": 10.4,
"firstService-4xx": 0.3,
"firstService-5xx": 0.2,
"secondService-2xx": 9.8,
"secondService-4xx": 0.1,
"secondService-5xx": 0.7
}
]
然后我有一个包含服务名称列表的数组:
var services = ["firstService", "secondService"]
最后我初始化了一个对象,它应该是结果的结构:
var obj = {
twoHundred: [],
fourHundred: [],
fiveHundred: []
};
var finalResult = {
"firstService" : obj,
"secondService": obj
}
我的函数的预期结果应该是:
finalResult = {
"firstService": {
twoHundred: [0.1, 10.4],
fourHundred: [0, 0.3],
fiveHundred: [1.2, 0.2]
},
"secondService": {
twoHundred: [5.4, 9.8],
fourHundred: [1, 0.1],
fiveHundred: [0.2, 0.7]
}
但我得到的是每个“代码”(2xx、4xx、5xx)的所有值都被推送到所有相应的数组中,甚至是不需要的服务。
payload.forEach(element => {
for (const [key, value] of Object.entries(element)) {
services.forEach(service => {
if (service == key.slice(0,-4)) {
if (key.includes("2xx")){
finalResult[service].twoHundred.push(value);
} else if (key.includes("4xx")){
finalResult[service].fourHundred.push(value);
} else if (key.includes("5xx")) {
finalResult[service].fiveHundred.push(value);
}
}
})
}
})
进行一些似乎与推送相关的调试,其余的检查工作。我还尝试了 FinalResult[service]["FiveHundred"].push(value) 的形式,但结果没有改变。 我也尝试更改代码、循环,但最终我总是得到这个(错误的)结果:
{
firstService: {
twoHundred: [ 0.1, 5.4, 10.4, 9.8 ],
fourHundred: [ 0, 1, 0.3, 0.1 ],
fiveHundred: [ 1.2, 0.2, 0.2, 0.7 ]
},
secondService: {
twoHundred: [ 0.1, 5.4, 10.4, 9.8 ],
fourHundred: [ 0, 1, 0.3, 0.1 ],
fiveHundred: [ 1.2, 0.2, 0.2, 0.7 ]
}
}
最佳答案
这里只有一个对象:
var obj = {
twoHundred: [],
fourHundred: [],
fiveHundred: []
};
以及对该一个对象的多个引用:
var finalResult = {
"firstService" : obj,
"secondService": obj
}
无论您使用哪个引用,当您将一个值推送到该一个对象上的数组时,该对象现在在其数组之一中具有该值。对该对象的任何引用都将看到该值,因为它们引用同一个对象。
听起来您想使用两个对象,例如:
var finalResult = {
"firstService" : {
twoHundred: [],
fourHundred: [],
fiveHundred: []
},
"secondService": {
twoHundred: [],
fourHundred: [],
fiveHundred: []
}
}
这样,对其中一个对象所做的任何更改都不会反射(reflect)在另一个对象中,因为它们是两个不同的对象。
关于javascript - 如何在 Javascript 中将数组中的元素插入键/值对象内?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75556339/