首页 > 解决方案 > 将 JSON 对象溢出到 Javascript 中的 JSON 数组对象

问题描述

我正在努力解决一个问题。我想使用 javascript 将 JSON 对象溢出到另一个 javascript 数组对象。JSON 应该拆分数组的最后一个元素。它意味着{ href: '/Local1', label: 'Local1', group: 'Local', active: ' active' }并且{ href: '/Local2', label: 'Local2', group: 'Local', active: ' active' }应该包含在Local数组中。{ href: '/Foreign1', label: 'Foreign1', group: 'Foreign', active: '' }并且{ href: '/Foreign1', label: 'Foreign1', group: 'Foreign', active: '' }应该在Forign数组中。

我在下面提到了尝试过的代码。但是我的代码没有给我预期的输出。我应该怎么做才能获得预期的输出?

exports.getMenu = function (selected, username) {
  const menu = [
    [
      ['/Local1', 'Local1', 'Local'],
      ['/Local2', 'Local2', 'Local'],
      ['/Foriegn1', 'Foriegn1', 'Foriegn'],
      ['/Foriegn2', 'Foriegn2', 'Foriegn'],
    ],
  ];

  const xxx = setMenuGroup(selected, menu);
  console.log(xxx);
  return xxx;

}

电流输出:

[
  [
    { href: '/Local1', label: 'Local1', group: 'Local', active: ' active' },
    { href: '/Local2', label: 'Local2', group: 'Local', active: '' },
    { href: '/Forign1', label: 'Forign1', group: 'Forign', active: '' },
    { href: '/Forign2', label: 'Forign2', group: 'Forign', active: '' }
  ]
]

预期输出:

{
  Local: [
    { href: '/Local1', label: 'Local1', group: 'Local', active: ' active' },
    { href: '/Local2', label: 'Local2', group: 'Local', active: '' },
  ],
  Forign: [
    { href: '/Forign1', label: 'Forign1', group: 'Forign', active: '' },
    { href: '/Forign2', label: 'Forign2', group: 'Forign', active: '' }
  ],
}

标签: javascriptarrays

解决方案


这对你有用吗?

input = [{
      href: '/Local1',
      label: 'Local1',
      group: 'Local',
      active: ' active'
    },
    {
      href: '/Local2',
      label: 'Local2',
      group: 'Local',
      active: ''
    },
    {
      href: '/Foreign1',
      label: 'Foreign1',
      group: 'Foreign',
      active: ''
    },
    {
      href: '/Foreign2',
      label: 'Foreign2',
      group: 'Foreign',
      active: ''
    },
];

var result = input.reduce((acc, value) => {
  if(value.group in acc){
    acc[value.group].push(value)
  } else {
    acc[value.group] = [value];
    }
    return acc
}, {})

console.log(result)


推荐阅读