首页 > 解决方案 > 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
    }
  },
 .......
}

我要求如果键已经存在,然后为它的对应键添加数组/对象

标签: javascript

解决方案


map() 函数返回一个新数组。要转换输出,您需要reduce(),也称为“折叠”。

arr.reduce((acc, curr) => {
  const split = curr.key.split('_');
  const identifier = split[0];
  const property = split[1];
  acc[identifier] = { ...acc[identifier], [property]: true };
  return acc;
}, {});

推荐阅读