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);
您必须首先过滤数组,然后映射它以获取所需的值..您可以尝试这样做
let result1 = obj["Roles"].filter(function(item) { return arr.includes(item.code)}).map(filteredObj => filteredObj.fullname);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.