javascript - 将 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: '' }
],
}
解决方案
这对你有用吗?
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)
推荐阅读
- javascript - 将 DOM 操作与轮播中的样式更改同步的问题
- node.js - 我怎样才能等到加载掩码在量角器中消失?
- python - 使用功能级别标记来确定应该在 after_scenario 中使用行为清理哪个场景
- python - 如何制作这样的循环 3 维?
- python - 在 Python matplotlib 中添加图例
- html - 仅在 Web 动画期间才考虑 60FPS 吗?
- fortran - 在数组 fortran 中查找非零元素的索引
- c++ - 线程彼此减慢
- javascript - 在 .env 文件中读取导出的变量 nodejs
- css - 阻止 @import CSS 的页面渲染