简体   繁体   English

通过数组的键将数组转换为对象

[英]Convert Array to Object by key of array

What is the best way to convert:转换的最佳方法是什么:

Dynamically I am getting an array.动态地我得到一个数组。

For example we can consider this following array.例如,我们可以考虑以下数组。

[
    'typeRead_1',
    'typeModify_1',
    'typeModify_2',
    'typeRead_3',
];

But I want it something like this.但我想要这样的东西。 to:至:

{
    1: {
      typeRead: true,
      typeModify: true,
    },
    2: {
      typeRead: false,
      typeModify: true,
    },
    3: {
      typeRead: true,
      typeModify: false,
    }
  };

Here is one way of doing this:这是执行此操作的一种方法:

 const items = [ 'typeRead_1', 'typeModify_1', 'typeModify_2', 'typeRead_3', ]; const ret = items.reduce((ret, el) => { let [prop, key] = el.split('_'); if (!ret[key]) ret[key] = { typeRead: false, typeModify: false }; ret[key][prop] = true; return ret; }, {}) console.log(ret)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM