In JavaScript I have an array of three letter codes and I have a JSON file that has values for each of these codes. I need to map the codes to the corresponding values in the JSON file. Here's an example:
{"Roles" : [
{"code": "cmm", "fullname": "commentator"},
{"code": "cmp", "fullname": "composer"},
{"code": "cnd", "fullname": "conductor"},
{"code": "cng", "fullname": "cinematographer"},
{"code": "cns", "fullname": "censor"},
{"code": "com", "fullname": "compiler"}
]}
var arr = ["cmm", "com", "cng"];
var mappedArray = arr.map( ??? );
//mappedArray now contains: ["commentator", "composer", "cinematographer"]
I can't think of a way of solving this that isn't horribly inefficient. Can anyone help?
You can achieve this using filter
var obj = {"Roles" : [
{"code": "cmm", "fullname": "commentator"},
{"code": "cmp", "fullname": "composer"},
{"code": "cnd", "fullname": "conductor"},
{"code": "cng", "fullname": "cinematographer"},
{"code": "cns", "fullname": "censor"},
{"code": "com", "fullname": "compiler"}
]}
var arr = ["cmm", "com", "cng"];
var mappedArray = obj["Roles"].filter(d => arr.includes(d.code))
console.log('Filtered Array', mappedArray)
console.log('Result', mappedArray.map(({fullname}) => fullname))
The most efficient way would still be to use a for/loop:
const data = {"Roles" : [{"code": "cmm", "fullname": "commentator"},{"code": "cmp", "fullname": "composer"},{"code": "cnd", "fullname": "conductor"},{"code": "cng", "fullname": "cinematographer"},{"code": "cns", "fullname": "censor"},{"code": "com", "fullname": "compiler"}]};
var arr = ["cmm", "com", "cng"];
const out = [];
for (let i = 0; i < data.Roles.length; i++) {
const el = data.Roles[i];
if (arr.indexOf(el.code) > -1) out.push(el.fullname);
}
console.log(out);
Using reduce is a little more functional/neater but won't be as efficient. You can pull out the data you want without the round trip of using filter then map.
const data = {"Roles" : [{"code": "cmm", "fullname": "commentator"},{"code": "cmp", "fullname": "composer"},{"code": "cnd", "fullname": "conductor"},{"code": "cng", "fullname": "cinematographer"},{"code": "cns", "fullname": "censor"},{"code": "com", "fullname": "compiler"}]};
var arr = ["cmm", "com", "cng"];
var out = data.Roles.reduce((acc, c) => {
if (arr.includes(c.code)) acc.push(c.fullname);
return acc;
}, []);
console.log(out);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With