我正在尝试从多维数组中检索单个结果,然后将该结果推送到对象数组中包含的每个对象。
这是我的代码;
var data = {
"questions": ["Q1", "Q2", "Q3"],
"details": [{
"name": "Alex",
"values": [27, 2, 14]
}, {
"name": "Bill",
"values": [40, 94, 18]
}, {
"name": "Gary",
"values": [64, 32, 45]
}]
}
var question = "Q1";
var singleResult = [];
for (var i = 0; i < data.details.length; i++) {
var qIndex = data.questions.indexOf(question)
singleResult.push(data.details[i].values[qIndex])
}
for (var i = 0; i < singleResult.length; i++) {
data.details.push({
single: singleResult[i]
})
}
console.log(data.details)
正如您所看到的那样,它正在将一个新对象推入到数组中,而我希望将单个结果推送到每个现有的3个对象中。
所以我的新数组应该是这样的;
[{
"name": "Alex",
"values": [27, 2, 14],
"single": 27
}, {
"name": "Bill",
"values": [40, 94, 18],
"single": 40
}, {
"name": "Gary",
"values": [64, 32, 45],
"single": 64
}]
我认为使用.concat
运行循环可以解决问题,但遗憾的是情况并非如此(至少对我而言!)。
希望一切都清楚,提前感谢任何帮助/进步!
答案 0 :(得分:2)
我会像这样重构它:
var data = {
"questions": ["Q1", "Q2", "Q3"],
"details": [{
"name": "Alex",
"values": [27, 2, 14]
}, {
"name": "Bill",
"values": [40, 94, 18]
}, {
"name": "Gary",
"values": [64, 32, 45]
}]
}
var question = "Q1";
var qIndex = data.questions.indexOf(question)
data.details.forEach((obj) => {
obj.single = obj.values[qIndex];
});
console.log(data.details)
亮点:
答案 1 :(得分:2)
您可以使用indexOf()
获取问题索引,然后使用map()
获取修改后的数组。
var data = {"questions":["Q1","Q2","Q3"],"details":[{"name":"Alex","values":[27,2,14]},{"name":"Bill","values":[40,94,18]},{"name":"Gary","values":[64,32,45]}]}
var question = "Q1";
var qIndex = data.questions.indexOf(question);
var result = data.details.map(function(e) {
var o = JSON.parse(JSON.stringify(e));
o.single = e.values[qIndex];
return o;
});
console.log(result);
&#13;
答案 2 :(得分:1)
var data = {
"questions": ["Q1", "Q2", "Q3"],
"details": [{
"name": "Alex",
"values": [27, 2, 14]
}, {
"name": "Bill",
"values": [40, 94, 18]
}, {
"name": "Gary",
"values": [64, 32, 45]
}]
}
var question = "Q1";
var singleResult = [];
for (var i = 0; i < data.details.length; i++) {
var qIndex = data.questions.indexOf(question)
singleResult.push(data.details[i].values[qIndex])
}
for (var i = 0; i < singleResult.length; i++) {
data.details[i].single = singleResult[i];
}
console.log(data.details)
&#13;
答案 3 :(得分:1)
oData model V2
&#13;