gpt4 book ai didi

javascript - 通过将所有唯一键的值相加并隐藏为分隔字符串来组合 JSON 对象中的项目

转载 作者:行者123 更新时间:2023-11-29 19:23:41 26 4
gpt4 key购买 nike

我有一个像这样的 JSON 或 Javascript 结构var myJSON=

{
"A":{
"59":"13",
"60":"13",
"61":"26",
"62":"10",
"63":"16",
"64":"19",
"65":"8",
"66":"9"
},
"B":{
"59":"11",
"60":"13",
"61":"22",
"62":"8",
"63":"8",
"64":"7",
"65":"21",
"66":"14"
},
"C":{
"59":"5",
"61":"0",
"62":"4",
"63":"4",
"65":"4"
}
}

但是我需要使用每个主要元素下的每个键的值从相同的结构构建另一个对象 enter image description here

所以输出就像一个分隔字符串,结合了上述 JSON 的所有唯一键。结果会是这样

59:29#60:26#61:48#62:22#63:28#64:26#65:33#66:23

结构中的所有键都必须在分隔字符串中。正如我在图片中突出显示的 59 它添加了所有 59

的值

最佳答案

var myJSON = {
"A": { "59": "13", "60": "13", "61": "26", "62": "10", "63": "16", "64": "19", "65": "8", "66": "9" },
"B": { "59": "11", "60": "13", "61": "22", "62": "8", "63": "8", "64": "7", "65": "21", "66": "14" },
"C": { "59": "5", "61": "0", "62": "4", "63": "4", "65": "4" }
}

var consolidatedObject = {};
// loop through the top level properties
for (var a in myJSON) {
if (myJSON.hasOwnProperty(a)) {
// add the keys and the values
for (var b in myJSON[a])
if (myJSON[a].hasOwnProperty(b)) {
consolidatedObject[b] = (consolidatedObject[b] | 0) + Number(myJSON[a][b]);
}
}
}

// beat into shape
console.log(JSON.stringify(consolidatedObject).replace(/"/g, '').replace(/,/g, '#').replace(/[{}]/g, ''));

var myJSON = {
"A": { "59": "13", "60": "13", "61": "26", "62": "10", "63": "16", "64": "19", "65": "8", "66": "9" },
"B": { "59": "11", "60": "13", "61": "22", "62": "8", "63": "8", "64": "7", "65": "21", "66": "14" },
"C": { "59": "5", "61": "0", "62": "4", "63": "4", "65": "4" }
}

var consolidatedObject = {};
// loop through the top level properties
for (var a in myJSON) {
if (myJSON.hasOwnProperty(a)) {
// add the keys and the values
for (var b in myJSON[a])
if (myJSON[a].hasOwnProperty(b)) {
consolidatedObject[b] = (consolidatedObject[b] | 0) + Number(myJSON[a][b]);
}
}
}

// beat into shape
alert(JSON.stringify(consolidatedObject).replace(/"/g, '').replace(/,/g, '#').replace(/[{}]/g, ''));

关于javascript - 通过将所有唯一键的值相加并隐藏为分隔字符串来组合 JSON 对象中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31876582/

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