Need alternate way for flatmap in javascript lower es5 version for the below mapping.
const b = [{
"errorname": [{
"name": "Error 01",
"desc_1": "Test: 01",
"desc_2": "Testing"
}, {
"name": "Error 03",
"desc_1": "Test: 03",
"desc_2": "Testing"
}],
}, {
"errorname": [{
"name": "Error 02",
"desc_1": "Test: 02",
"desc_2": "Testing"
}, {
"name": "Error 09",
"desc_1": "Test: 09",
"desc_2": "Testing"
} ]
}];
var errorMap = new Map(b
.flatMap(o => o.errorname)
.map(({
name,
...e
}) => [name, e]));
console.log(errorMap)
.as-console-wrapper {
max-height: 100% !important;
top: 0;
}
trying for es5 with a similar kind of operation. The application is accessed using electron app which doesnot support es9
You can download a polyfill or implement your own. It should be like this
Array.prototype.flatMap = function(mapper) {
var result = [];
for (var i = 0; i < this.length; ++i) {
var item = mapper(this[i], i, this);
if (!Array.isArray(item)) {
item = [item];
}
for (var j = 0; j < item.length; ++j) {
result.push(item[j]);
}
}
return result;
}
Then you will be able to call myArray.flatMap as you would do normally.
You can do an inner-outer reduce by nesting the calls. This will work for an ECMAScript version under 5/6.
const b = [{
"errorname": [
{ "name": "Error 01", "desc_1": "Test: 01", "desc_2": "Testing" },
{ "name": "Error 03", "desc_1": "Test: 03", "desc_2": "Testing" }],
}, {
"errorname": [
{ "name": "Error 02", "desc_1": "Test: 02", "desc_2": "Testing" },
{ "name": "Error 09", "desc_1": "Test: 09", "desc_2": "Testing" }
]
}];
var errorMap = b.reduce(function(outer, group) {
return group.errorname.reduce(function(inner, item) {
return inner.set(item.name, {
desc_1: item.desc_1,
desc_2: item.desc_2
});
}, outer);
}, new Map);
console.log(Object.fromEntries([...errorMap]));
.as-console-wrapper { max-height: 100% !important; top: 0; }