I have source data which follows the following format where I have a collection of values per category
var data = [
{'name': 'Test 1',
'values': {
'50':0,
'51':10,
'52':0,
'53':10,
'54':60,
'55':999
}},
{'name': 'Test 2',
'values': {
'50':33,
'51':3,
'52':333,
'53':3,
'54':3,
'55':3333
}},
{'name': 'Test 3',
'values': {
'50':55,
'51':66,
'52':77,
'53':88,
'54':99,
'55':100
}}];
I need to pivot this to create an array for each value individually. So my result set would be
var result = [
{'value':50, 'Test 1':0, 'Test 2':33, 'Test 3': 55},
{'value':51, 'Test 1':10, 'Test 2':3, 'Test 3': 66},
{'value':52, 'Test 1':0, 'Test 2':333, 'Test 3': 77},
{'value':53, 'Test 1':10, 'Test 2':3, 'Test 3': 88},
{'value':54, 'Test 1':60, 'Test 2':3, 'Test 3': 99},
{'value':55, 'Test 1':999, 'Test 2':3333, 'Test 3': 100}
]
I cannot see how to create new new array by looping through the data array
asked Sep 10, 2019 at 12:44
Mike
2,5876 gold badges38 silver badges76 bronze badges
-
would be easier to "see" if you formatted your data.I wrestled a bear once.– I wrestled a bear once.2019年09月10日 12:45:54 +00:00Commented Sep 10, 2019 at 12:45
-
Can Ia sk how I do that?Mike– Mike2019年09月10日 12:47:33 +00:00Commented Sep 10, 2019 at 12:47
2 Answers 2
You could take an object for collecting same keys and get the values from the object as result set.
var data = [{ name: 'Test 1', values: { 50: 0, 51: 10, 52: 0, 53: 10, 54: 60, 55: 999 } }, { name: 'Test 2', values: { 50: 33, 51: 3, 52: 333, 53: 3, 54: 3, 55: 3333 } }, { name: 'Test 3', values: { 50: 55, 51: 66, 52: 77, 53: 88, 54: 99, 55: 100 } }]
result = Object.values(data.reduce((r, { name, values }) => {
Object.entries(values).forEach(([k, v]) => {
r[k] = r[k] || { value: +k };
r[k][name] = v;
});
return r;
}, {}));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
answered Sep 10, 2019 at 13:03
Nina Scholz
388k26 gold badges367 silver badges417 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
There may be more efficient ways to do this but this is very fault tolerant in case your data is not so clean.
var data = [
{'name': 'Test 1',
'values': {
'50':0,
'51':10,
'52':0,
'53':10,
'54':60,
'55':999
}},
{'name': 'Test 2',
'values': {
'50':33,
'51':3,
'52':333,
'53':3,
'54':3,
'55':3333
}},
{'name': 'Test 3',
'values': {
'50':55,
'51':66,
'52':77,
'53':88,
'54':99,
'55':100
}}];
var piv_data = [];
for(var i = 0; i < data.length; i++)
{
var name = data[i].name;
for(var value in data[i].values)
{
var index = -1;
for(var x=0; x < piv_data.length; x++)
{
if(piv_data[x].value == value)
{
index = x;
break;
}
}
if(index == -1)
{
piv_data.push({ 'value': value })
index = piv_data.length -1;
}
piv_data[index][name] = data[i].values[value]
}
}
console.log(piv_data)
Comments
lang-js