Reputation: 35
{Test1: 11, Test2: 25, Test3: 4, others: 5, others: 9, others: 11, others: 13, others: 27}
I am getting this object in return and my requirement is to show it like:
{Test1: 11, Test2: 25, Test3: 4, others: 65}
Where 65 is the sum of all values with a others
key.
Below is the code.
openTypeCaseChart.data.labels = $.map(countJson['types'], function(obj, index) {
var retObj;
if (index <= 2){
retObj = obj['type_label'] + " " + obj['open'];
return retObj;
} else {
total += obj['open']
retObj = obj['type_label'] = "others"+ " " + total;
}
console.log("retObj: "+retObj);
}
Upvotes: 0
Views: 72
Reputation: 146
I suppose you have input in this format:
const countJson = {
types: [
{
type_label: 'Test1',
open: 11,
},
{
type_label: 'Test2',
open: 25,
},
{
type_label: 'Test3',
open: 4,
},
{
type_label: 'Test4',
open: 5,
},
{
type_label: 'Test5',
open: 9,
},
{
type_label: 'Test6',
open: 11,
},
{
type_label: 'Test7',
open: 13,
},
{
type_label: 'Test8',
open: 27,
},
],
// ...
};
Then you can use this function that takes your countJson object as an input and returns a string with keys less than index 2 with their original keys (Test1, Test2, Test3) and all items above those with their values summed and merged into a single key 'others':
const mergeCounts = countJson => {
const itemsObj = countJson.types
.reduce((obj, item, i) => {
const k = item.type_label;
const v = item.open;
// for all items after index 2, sum and merge them into a single key 'others'
if (i > 2) {
const othersValue = v + (obj['others'] || 0);
return {
...obj,
'others': othersValue,
};
}
// for items up to index 2, return key value pairs
return {
...obj,
[item.type_label]: item.open
};
}, {})
// At this point, you get:
// itemsObj = { Test1: 11, Test2: 25, Test3: 4, others: 65 }
return Object.keys(itemsObj)
.map((k, i) => `${k} ${itemsObj[k]}`)
.join(','); // this results: Test1 11,Test2 25,Test3 4,others 65
};
console.log(
mergeCounts(countJson) // results: Test1 11,Test2 25,Test3 4,others 65
);
Upvotes: 1
Reputation: 119
You can use for in loop for your requirement. Example
for(let key in object)
{
console.log(key +" "+object[key])
}
Upvotes: 0