简体   繁体   English

使用JSON文件的JavaScript地图数组

[英]JavaScript map array using JSON file

In JavaScript I have an array of three letter codes and I have a JSON file that has values for each of these codes. 在JavaScript中,我有一个包含三个字母代码的数组,我有一个JSON文件,其中包含每个代码的值。 I need to map the codes to the corresponding values in the JSON file. 我需要将代码映射到JSON文件中的相应值。 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 : 最有效的方法仍然是使用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. 使用reduce更实用/更整洁,但效率不高。 You can pull out the data you want without the round trip of using filter then map . 您可以提取所需的数据,而无需使用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); 

您必须首先过滤数组,然后映射它以获取所需的值..您可以尝试这样做

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM