I possess a dataset and desire to correlate each element to different elements

[
    {
        "clauseId": 1,
        "clauseName": "cover",
        "texts": [
            {
                "textId": 1,
                "text": "hello"
            }
        ]
    },
    {
        "clauseId": 3,
        "clauseName": "xyz",
        "texts": [
            {
                "textId": 3,
                "text": "hello Everyone"
            },
            {
                "textId": 4,
                "text": "Some data"
            }
        ]
    },
    {
        "clauseId": 2,
        "clauseName": "joining",
        "texts": [
            {
                "textId": 3,
                "text": "hello1"
            },
            {
                "textId": 4,
                "text": "hello2"
            }
        ]
    }
]

If I create a list like

a=[joining,cover]

I expect a new list to be generated as

b=[hello1,hello2,hello]

It's important to note that the index of each element matters. If I reverse the index, the

b =[hello,hello1,hello2]

If

a=[xyz,joining,cover]
b=["hello Everyone","Some data",hello1,hello2,hello]

Similarly, if I change the order in list 'a' to [joining,xyz,cover]

b=["hello1","hello2","hello Everyone","Some data",hello]

It should be noted that the input data may include multiple clause names and text entries. This is just a demonstration.

Answer №1

To extract a lookup table from the original array, you can utilize a Map. In this Map, each clauseName serves as the key pointing to an array of texts as the corresponding value. Subsequently, you can apply .flatMap() on your clauses array to access the values stored under each key in the lookup table (i.e., the Map).

Check out the example below:

const arr=[{clauseId:1,clauseName:"cover",texts:[{textId:1,text:"hello"}]},{clauseId:3,clauseName:"xyz",texts:[{textId:3,text:"hello Everyone"},{textId:4,text:"Some data"}]},{clauseId:2,clauseName:"joining",texts:[{textId:3,text:"hello1"},{textId:4,text:"hello2"}]}];

const clauses = ["joining", "cover"];
const lut = new Map(arr.map(({clauseName, texts}) => 
  [clauseName, texts.map(({text}) => text)]
));

const result = clauses.flatMap(key => lut.get(key));
console.log(result);

If you are unable to utilize the native .flatMap implementation in JavaScript, you have the option to either polyfill it or employ lodash's implementation:

const arr = [{clauseId:1,clauseName:"cover",texts:[{textId:1,text:"hello"}]},{clauseId:3,clauseName:"xyz",texts:[{textId:3,text:"hello Everyone"},{textId:4,text:"Some data"}]},{clauseId:2,clauseName:"joining",texts:[{textId:3,text:"hello1"},{textId:4,text:"hello2"}]}];

const clauses = ["joining", "cover"];
const lut = new Map(arr.map(({clauseName, texts}) => 
  [clauseName, texts.map(({text}) => text)]
));

const result = _.flatMap(clauses, key => lut.get(key));
console.log(result);
<script src="https://cdn.jsdelivr.net/lodash/4.16.4/lodash.min.js"></script>

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

Sending user input from search component to main App.js in React

I'm currently working on an app that searches a Movies database API. I have a main fetch function in App.js, and in tutorials, people are using a search bar within this main APP component. I'm wondering if it would be better to create a separate ...

Guide on increasing a basic counter and a counter with an object component using redux

(I need help fixing my code) I am trying to write a counter increment code to better understand Redux in the following situations: Increasing a simple counter Increasing a counter with an object Currently facing an issue where counter1 is undefined on the ...

The JQuery-AJAX script in my Django application, intended to show a preset value in a calculated field, is not functioning as expected

Here are a couple of models from my project: class Package(models.Model): patient=models.ForeignKey(Patient, on_delete=CASCADE) diagnosis=models.ForeignKey(Diagnosis, on_delete=CASCADE) treatment=models.ForeignKey(Treatment, on_delete=CASCADE) ...

Feeling puzzled by the code snippet for vuejs-templates using webpack-simple?

Just starting out with javascript. Learning Vue.js through example reading. But feeling confused by the code snippet from vuejs-templates/webpack-simple. Specifically line 25 data () { return { msg: 'Welcome to Your Vue.js App' ...

What steps should I take to ensure that clicking this button triggers the API request and returns the data in JSON format?

I'm attempting to have the button with id 'testp' return an api request in json format, however it seems to not be functioning properly. You can find the HTML code link here: https://github.com/atullu1234/REST-API-Developer-1/blob/main/js-bu ...

How to Overcome Read-only HTML Components in Selenium with Python?

I am working on automating a task using Selenium in Python, and part of it involves selecting a date. The website I am testing has an input box for date selection that displays a standard date table when clicked. Unfortunately, the input text box is read- ...

What solutions are available to resolve the routing problem in React.js?

On my fourth day working with Node and React.js, I am creating a custom offline search function for Docusaurus 2. I've built a JSON index and implemented a search function using elasticlunr. My goal is to redirect to a separate results page, but I&apo ...

Each keystroke is saved individually in an array, thanks to React, instead of storing the entire text

Hey everyone, I have a task to develop a full-stack web application that allows users to create meals with ingredients, preparation details, and cooking time. I am using MongoDB, Node.js, Express, and React for this project. Everything works fine when test ...

Executing Angular via C# - Carrying out NUnit tests

Within our solution, we have an API, Angular application, and NUnit test project. My responsibility is to examine the user interface of the Angular app through NUnit tests. Is there a method to launch the Angular application directly from the test setup? ...

transferring information between two sibling elements in Angular 7

My goal is to display the username of the logged-in user on the home page. I have a LoginComponent, HomeComponent, and I am using a service called DataService.ts for data transfer. The data seems to be reaching DataService.ts but it's not getting to t ...

The function insertAdjacentHTML does not seem to be functioning properly when used with a

I am working with a parent element that contains some child elements. I create a DocumentFragment and clone certain nodes, adding them to the fragment. Then, I attempt to insert the fragment into the DOM using the insertAdjacentHTML method. Here is an ex ...

Strategies for mitigating the use of Observables when passing data between Angular routes

When trying to exchange data between routes, the most effective method appears to be using a service. To ensure that data is updated and re-rendered in the view, we are required to utilize BehaviorSubject. Based on my understanding, a simple component wou ...

Guide on redirecting to a specific Vue-app page using Flask

I am currently working on an application that includes a page that ends with '@' and provides meta information for the page without '@'. For example, if the page '/user/aabb' contains information about the user 'aabb&apos ...

Differences: Angular ngController vs Controller embedded in Directive

I'm interested in exploring the various scenarios where these two methods of creating a controller can be used: Using ngController: myApp.controller('myController', ['$scope', function ( $scope ) { }]); Creating the controller ...

Facing an ESIDIR error in NextJs, despite the fact that the code was sourced from the official documentation

For an upcoming interview, I decided to dive into learning Next.js by following the tutorial provided on Next.js official website. Everything was going smoothly until I reached this particular section that focused on implementing getStaticProps. Followin ...

What is the process for building an interactive quiz using JavaScript?

In the process of creating a quiz, I envision a user interface that presents questions in a "card" format. These questions will include simple yes/no inquiries and some multiple-choice options. As the user progresses through the quiz, their answers will de ...

On production, Heroku fails to load JavaScript files, only allowing CSS files to be loaded. However, the files load successfully when

I've been struggling to find a solution to my problem, so I'm reaching out for some help. I am in the process of deploying my node (express) app to Heroku, but I've encountered an issue where only CSS files from my public folder are being t ...

What steps should I take to ensure that the proper link is loaded and opened when the loop is clicked?

I've been working on a script to display the top 25 posts from reddit and have their respective links open in a sliding div below. However, I'm running into an issue where the script outputs the same post for every item in the loop. I understand ...

How can I determine whether a list is sorted or not, and how do I display this information on the console

I have developed a program that can determine whether a given list is sorted or not. Now, I am looking for guidance on how to print out the answer indicating whether the list is sorted or not (e.g., "The list is sorted" or "The list is not sorted"). pub ...

Guide on how to retrieve information from an API and populate it into a dropdown menu

Currently, I am developing an MVC application that interacts with an API. My goal is to call a specific method from the API in order to populate data into a combo-box. However, as a newcomer to this technology, I am unsure of the best approach to take. An ...