gpt4 book ai didi

Javascript 合并键和值

转载 作者:行者123 更新时间:2023-12-02 21:56:27 25 4
gpt4 key购买 nike

{Test1: 11, Test2: 25, Test3: 4, others: 5, others: 9, others: 11, others: 13, others: 27}

我得到这个对象作为返回,我的要求是显示它:

{Test1: 11, Test2: 25, Test3: 4, others: 65}

其中 65 是带有 others 键的所有值的总和。

下面是代码。

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);

}

最佳答案

我想您的输入格式如下:

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,
},
],
// ...
};

然后您可以使用此函数,该函数将您的 countJson 对象作为输入,并返回一个键小于索引 2 的字符串及其原始键(Test1、Test2、Test3)以及所有高于这些项目的值,并将它们的值相加并合并到单键“其他”:

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
);

关于Javascript 合并键和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59999013/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com