javascript - Javascript:检查是否存在重复键,为重复键添加相应的子项
问题描述
我试图找出一个示例对象数组,其中我有以下键值对。我需要根据下划线找到要拆分的键,第一个拆分的值将成为键,第二个将成为该键的对象数组。我得到了需要唯一的重复键,然后将值添加到其中。
const arr = [
{label: 'id', key: 'wfc_id'},
{label: 'Name', key: 'wfc_name'},
{label: 'Age', key: 'wfc_age'},
{label: 'id', key: 'ga_id'},
{label: 'Name', key: 'ga_name'},
{label: 'Age', key: 'ga_age'},
{label: 'Name', key: 'rtc_name'},
{label: 'id', key: 'rtc_id'},
]
Desired Ouput:
output = {
wfc: {id:true, name:true, age: true},
ga: {id:true, name:true, age: true},
rtc: {id:true, name:true},
}
我尝试了以下代码:
let output = Object.assign({},arr.map((item) => {
let str = item.key.split('_');
let obj = {};
obj[str[0]] = {
[str[1]]: true
}
return obj
})
);
console.log(output);
但它给了我输出
{
"0": {
"wfc": {
"id": true
}
},
"1": {
"wfc": {
"name": true
}
},
"2": {
"wfc": {
"age": true
}
},
"3": {
"ga": {
"id": true
}
},
"4": {
"ga": {
"name": true
}
},
"5": {
"ga": {
"age": true
}
},
.......
}
我要求如果键已经存在,然后为它的对应键添加数组/对象
解决方案
推荐阅读
- amazon-sagemaker - 在本地模式下运行 sagemaker python sdk sklearn 时出现 S3 权限错误
- wix - NOT UPGRADINGPRODUCTCODE 在自定义操作的重大升级时评估为 true
- reactjs - 仅在 Gatsby 的特定页面上加载 Snipcart
- sql - SQL:如何获取下一个非空值
- java - Java图像裁剪打破了libpng的PNG
- c++ - Boost Graph Library,修复节点大小
- arrays - Typescript - Check values in one array are present in another
- c# - WPF 设计器问题(mahapps Metro)?
- python - 在pandas python中逐列计算匹配部分字符串的出现次数
- python - LDA Mallet 替代 get_document_topics - 衡量每个文档的主题