const input = [{
"type": "group1@action1",
"label": "labelA",
"placeholders": ["b", "a", "r"]
}, {
"type": "group1@action2",
"label": "labelB",
"placeholders": ["x", "y", "z"]
}, {
"type": "group2@action123",
"label": "labelC",
"placeholders": ["a", "b", "c"]
}];
And I want
[
{
"group": "group1",
"items": [
{
"action": "action1"
"label": "labelA",
"placeholders": ["b", "a", "r"]
},
{
"action": "action1"
"label": "labelB",
"placeholders": ["x", "y", "z"]
}
]
},
{
"group": "group2",
"items": [
{
"action": "action123"
"label": "labelC",
"placeholders": ["a", "b", "c"]
}
]
}
]
My javascript code for split:
var key = "group1@action1";
console.log(key.substring(0,key.indexOf('@')));
console.log(key.substring(key.indexOf('@')-1, key.length));
I try use a Map() but the result is not my target. I need help by a javascript developer (Is not my job at 100%).
output = new Map;
input.forEach(element => {
group = element.type.substring(0,element.type.indexOf('@'));
action = element.type.substring(element.type.indexOf('@')-1, element.type.length)
if (!output.has(group)) {
output.set(group, [element]);
} else {
output.get(group).push(element);
}
});
console.log(output);
actualy result is
Map(2) {
'group1' => [
{ type: 'group1@action1', label: 'labelA', placeholders: [Array] },
{ type: 'group1@action2', label: 'labelB', placeholders: [Array] }
],
'group2' => [
{
type: 'group2@action123',
label: 'labelC',
placeholders: [Array]
}
]
}
I try use console.log(Object.fromEntries(output));
but the result is:
{
group1: [{
label: "labelA",
placeholders: ["b", "a", "r"],
type: "group1@action1"
}, {
label: "labelB",
placeholders: ["x", "y", "z"],
type: "group1@action2"
}],
group2: [{
label: "labelC",
placeholders: ["a", "b", "c"],
type: "group2@action123"
}]
}