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

发布于 2025-02-09 13:26:51 字数 405 浏览 1 评论 0原文

最好的转换方法是什么:

动态地得到一个数组。

例如,我们可以考虑以下数组。

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

但是我想要这样的东西。 到:

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

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,
    }
  };

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

卖梦商人 2025-02-16 13:26:51

这是这样做的一种方法:

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)

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)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文