I'm trying to retrieve a single result from a multi-dimensional array and then push that result into each object contained within an object array.
Here is my code;
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)
As you can see it is pushing a new object into the array where as instead I would like the single result to be pushed into each of the existing 3 objects.
So my new array should look like;
[{
"name": "Alex",
"values": [27, 2, 14],
"single": 27
}, {
"name": "Bill",
"values": [40, 94, 18],
"single": 40
}, {
"name": "Gary",
"values": [64, 32, 45],
"single": 64
}]
I thought running a loop with .concat would do the trick, but sadly it wasn't the case (for me at least!).
Hope everything is clear, thanks in advance for any help/advance!