javascript - 合并和求和数组对象Javascript
问题描述
我有一个对象数组。如果属性相同,我需要合并数组的元素,tag
然后counter
对这些对象的属性求和。
这是我的示例数组:
[
{
"tag": "#sala",
"state": {
"counter": 1
}
},
{
"tag": "#sala",
"state": {
"counter": 2
}
}
]
这是合并后数组的样子:
[
{
"tag": "#sala",
"state": {
"counter": 3
}
}
]
解决方案
您可以使用数组归约函数并在归约回调中使用findIndex
来检查累加器数组是否具有具有相同标签的对象。如果找到具有相同标签的对象,则更新该对象中的计数器,否则将当前对象推入累加器数组
let data = [{
"tag": "#sala",
"state": {
"counter": 1
}
},
{
"tag": "#sala",
"state": {
"counter": 2
}
}
];
let newData = data.reduce(function(acc, curr) {
let findTagIndex = acc.findIndex(item => item.tag === curr.tag);
if (findTagIndex === -1) {
acc.push(curr)
} else {
acc[findTagIndex].state.counter += curr.state.counter
}
return acc;
}, []);
console.log(newData)
推荐阅读
- java - TestNG 中的注释是强类型的。这是什么意思?
- c++ - getline 循环禁用打印到 txt
- tfs - 导入包含任务组的任务组
- c++ - Raspberry Pi 上的 Portaudio,找不到输入流的设备
- scala - Scala:使用同名的函数和内部对象
- firebase - Flutter 从 QuerySnapshot 转换为 Future
- >>
- android - Android 在preferences.xml 文件上使用字符串资源
- json - json在powershell中展开
- javascript - FCC Refactor Global Variables Out of Functions,数组未同时使用两种方法
- javascript - 在所见即所得编辑器中上传和显示图像