在JavaScript中,我有一个由三个字母代码组成的数组,并且有一个JSON文件,其中包含每个代码的值。我需要将代码映射到JSON文件中的相应值。 这是一个示例:
{"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"]
我想不出一种解决方法,该方法并非效率极低。有人可以帮忙吗?
答案 0 :(得分:2)
您可以使用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))
答案 1 :(得分:1)
最有效的方法仍然是使用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);
使用reduce
更具功能/外观,但效率不高。您可以使用filter
然后 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);
答案 2 :(得分:0)
您必须首先过滤数组,然后将其映射以获取所需的值。 你可以试试这个
TextView,ButtonView