JavaScript map array using JSON file

Viewed 3407

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?

3 Answers

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);

You have to first filter the array and then map it to get the required values.. you can try this

let result1 = obj["Roles"].filter(function(item) { return arr.includes(item.code)}).map(filteredObj => filteredObj.fullname);
Related