Using a JSON file to map an array in JavaScript

Looking to connect an array of three-letter codes in JavaScript with corresponding values stored in a JSON file. Let's illustrate with 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"]

Struggling to find an efficient solution for this problem. Any suggestions?

Answer №1

To accomplish this task, you can utilize the filter method

var 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 codes = ["cmm", "com", "cng"];

var filteredData = data["Roles"].filter(item => codes.includes(item.code))

console.log('Filtered Data:', filteredData)

console.log('Result:', filteredData.map(({fullname}) => fullname))

Answer №2

To efficiently extract specific data, using a for/loop is still the preferred method:

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

Although using reduce provides a more functional and cleaner approach, it may not be as efficient. It allows direct extraction of desired data without the need for filter followed by 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);

Answer №3

To retrieve the necessary values, you must filter the array before mapping it. Give this a shot:

let output = object["Roles"].filter(function(item) { return arr.includes(item.code)}).map(filteredObject => filteredObject.fullname);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the method for flipping a JSON object?

I recently came across a function that passes JSON in its parameter... { "code":0, "payload":[ { "time":1349661897, "packages":[ "49381" ], "ign":"PurpleArrow", "price":"15.99", ...

Exploring the functionality of AngularJS routing on a webpage

Testing the routing functionality of AngularJS while creating a web page. The index.html will contain links to Home, Courses, and Students. Clicking on each link will load its respective HTML using AngularJS routing. The student information is stored in ...

Is it possible to store hundreds of thousands of 10-character strings within an array in MongoDB design?

In the process of database design, I have created two tables for handling user-following-celebrity relationships. The first table, named "user_follow," stores users and an array of celebrities they are following (e.g., {"user_name": "mak", "follows": ["Tom ...

Issue: The system is unable to locate the module titled '@kyleshockey/object-assign-deep'

Recently, I installed the accept-language npm module. When attempting to start my project afterwards, an error message appeared: Error: Cannot find module '@kyleshockey/object-assign-deep' What steps can I take to fix this problem? ...

Is it possible to utilize the NavigationTimingAPI with asynchronous requests?

Currently, I am working on implementing performance measuring functionality in our project that utilizes custom elements v1. The NavigationTimingAPI provides detailed measurements for various navigation types (navigate, reload, browser back/forward): htt ...

Customize ACF Google Map - Adjusting the Look?

I have successfully set up and running a Wordpress site, where I utilized the ACF plugin to create a Google Map field. Everything is working fine, but I wish to modify the default style of the map. I specifically need a lighter grayscale theme for my websi ...

Changing background color using jQuery ID selector

Within thisid, the id of an html element is stored. In order to modify its background color, the code below can be utilized: let thisid = 'test'; $("a#" + thisid).css("background-color", "yellow"); <script src="https://cdnjs.cloudflare.com/a ...

Troubleshooting the CORS problem with 'Access-Control-Allow-Origin' while combining Vue.js for the front-end and Express for the back-end

While attempting to make a call to my API on Jazz using Vue.js and Axios, I encountered the following error: Access to XMLHttpRequest at ' _here' from origin 'http://localhost' has been blocked by CORS policy: Response to preflight ...

Building Your Own Custom Mobile Global Breakpoint Plugin with Vuetify in Nuxt.js

Looking to set up a custom breakpoint system for my Nuxt/Vuetify project so I can easily manage it from one centralized location instead of using $vuetif.breakpoint..... etc To achieve this, I have created a plugin file named mobile.js. While it functions ...

Embed HTML code into a React/Next.js website

I've been given the task of enhancing the UI/UX for an external service built on React (Next.js). The company has informed me that they only allow customization through a JavaScript text editor and injecting changes there. However, I'm having tro ...

Harnessing the Power: Ajax Combined with JQuery

I am facing an issue with my function where I make an ajax request, wait for a response, and return a value but the returned value is coming out as undefined. What could be causing this problem? function RetrieveDataFromURL(url){ return $.ajax({ ...

What is preventing bots and crawlers from detecting Next.js meta tags?

I'm currently using Next.js with Typescript and MongoDB to retrieve data. I'm encountering difficulties in rendering the page because the crawler is unable to detect the meta tags. For instance, Bing Search Engine claims that Title and Meta desc ...

Generating a constantly evolving 3D model and keeping it current within a web browser

My website already has a large user base, and I am looking to create a 3D visual representation of data on one of the pages. This model needs to be easily updatable based on each user's database information (imagine a square board with a ball whose po ...

Changing Json format into a Google Datastore Entity

I have been working on a Java application in Android Studio and I need to retrieve some entities that I stored in Google Datastore. These entities were originally stored as a List of Entities and then converted to JSON. However, I am now facing difficultie ...

Looking to learn how to utilize the setInitial method in Java programming?

Can someone help me write a method in Android Studio using setInitial(int[] x) to set the first 3 indices of an array to specific values (10, 100, and 342) and then return the modified array? I am struggling with this assignment and need assistance within ...

Discover the worth chart with JQ

I have a large JSON file that requires transforming some values based on a specific mapping. The current data structure is as follows: [ {"id":1, "value":"yes"}, {"id":2, "value":"no"}, {"id":3, "value":"maybe"} ] I aim to convert it into th ...

Generate a new tree structure using the identifiers of list items within an unorganized list

Attempting to convert the id's of li's in a nested unordered list into valid JSON. For example, consider the following list. To be clear, the goal is not to create the UL list itself, but rather the JSON from the li id's <ul class="lis ...

Converting user input from a string to an object in JavaScript: a comprehensive guide

Is there a way to transform user input string into objects when given an array of strings? ["code:213123", "code:213123", "code:213123"] I am looking to convert this array into an array of objects with the following format: [{code: "213123"},...] ...

Using node.js to make an HTTP request and parse JSON data with the

I am currently working on developing a web application using node.js that needs to interact with a PHP API. My goal is to request a JSON object from the PHP API, which I can then use in one of my .ejs templates. Below is the code snippet for my node.js im ...

Can a prototype be created in JavaScript for a "FileList" object type that enables the construction and addition of a "File" object within it?

This is my first time attempting to create a prototype, and I'm struggling to grasp the concept of callback functions. My current project involves automating the firmware update process for our company's routers using Python, Selenium, and Phant ...