Matching objects in an array based on a specific property using the key of another object

To display information in the UI based on matching values between the data.examples array object's name.value property and the keys in the wcObject.notCoveredList, we need to create a logic. If there is a match, all corresponding values from wcObject will be pushed into an array for display. In cases where there isn't a match, the value of the name.desc property from data.examples array object will be used, with the "not covered" text at the end removed.


    data = {
        examples : [
          {
            name: {
              value:"someOne",
              desc: "some random word not covered"
            },
            type: {
              value:"General",
              desc:"General"
            }
          }, {
            name: {
              value:"secondOne",
              desc: "second on in the queue not covered"
            },
            type: {
              value:"General",
              desc:"General"
            }
          }, {
            name: {
              value:"thirdOne",
              desc: "third one from the last not covered"
            },
            type: {
              value:"General",
              desc:"General"
            }
          }
        ]
 
 wcObject = {
    notCoveredList : [
      { someOne: "anyone can start " },
      { secondOne: "second One cannot start" },
      { thirdOne: "third One can be allowed" }
    ]
  }

Answer №1

This piece of code performs the following actions:

  1. It creates a filter object by extracting all the keys from wcObject.notCoveredList and turning them into keys in a single object with an undefined value. This allows for quicker lookup using a single hasOwnProperty() call instead of iterating through an array when filtering.
  2. Each element in the data.examples array is mapped to either its own name.desc property or, if applicable, the name.value property stripped of ' not covered'.

The snippet proceeds as follows:

wcNotCoveredKeys = wcObject.notCoveredList.reduce((memo, item) => {
  // Only interested in keys, values are empty.
  memo[Object.keys(item)[0]] = undefined;
  return memo;
}, {})

// With our lookup table established, we proceed:
forUI = data.examples.map(example => {
  if (wcNotCoveredKeys.hasOwnProperty(example.name.value)) {
    return example.name.value;
  }
  else {
    notCoveredString = example.name.desc;
    cutOutIndex = notCoveredString.indexOf(' not covered');
    return notCoveredString.slice(0, cutOutIndex)
  }
});

(updated with string slicing integration)

To clarify: removing the second item from wcObject.notCoveredList would result in the following output in forUI (based on the provided data structures/values):

["someOne", "second one in the queue", "thirdOne"]

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

Error: the specified item is not a valid function

As a newcomer to the world of JavaScript, I am eager to learn and explore new concepts. Currently, my focus is on centralizing the code for accessing my MySQL database within my Express JS server using promises. Below is an attempt I have made in achieving ...

Transforming an object containing methods into a string using Javascript specifically for Photoshop

I have a unique universal object that is essential for my Photoshop scripts. It contains various properties and methods like this: var Object = {}; Object.text = "this is some text"; Object.toolbox = new ToolBox(); // specialized object with its own funct ...

Is it possible to execute a URL twice instead of just once in AngularJS?

While developing a web application with AngularJS and Rest Web services, I encountered a problem where the URL is being executed twice instead of just once. I have created a service function for executing the web service API and calling it from the control ...

object passed as value to competent parent

I'm facing an issue where I am trying to pass a value to the parent component, but it is returning an object instead of the expected value. Here's what I have: Child Component render() { return ( this.props.data.map((val, idx) => { ...

What is the reason for the difference in behavior between declaring "Germ" as an Rvalue array object and as a pointer in an assignment statement?

I appreciate your patience as I include some additional, secondary questions within this post rather than creating separate ones. When we have a declaration like char name[]="Germ";, the identifier Germ is considered of type char[5], correct? However, in ...

What is the best way to merge and nest connected JSON elements?

I am working with two separate JSON files that I need to merge into one single JSON object for use on the frontend of my project. fragments.json [ { "id": 2, "title": "John Smith is nice", "reports& ...

Improve your JavaScript form by implementing a time loading feature!

I am currently developing a sign-up form using native JavaScript and Ajax. The form utilizes an Ajax function to transmit data to a PHP engine, which then performs database queries. My main concern is implementing a loading function in JavaScript that can ...

Guide on setting up an Express application to control LED light strips with a Raspberry Pi3

After setting up a node server on my Raspberry Pi to control an Adafruit Dotstar light strip, I encountered a problem. The sequence of colors on the light strip is triggered by an HTTP request to localhost:8000/fade, causing the server to run fade.js endle ...

Is there a way to handle an error or display N/A when an object is not found in the JSON data I am working with?

Today's games lineup and broadcasting channels can be displayed using this JSON format. However, I am encountering the following error: TypeError: /home/ubuntu/workspace/sportsapp/views/results.ejs:8 6| <% data["games"].forEach(function(game){ ...

Processing JSON Serialization from Controller to AJAX Response

I'm struggling to find the correct way to use an HttpWebRequest, and then convert its response into a readable format of JSON for a JavaScript AJAX function. If I just return the raw text, it includes escaping slashes in the response. If I deserializ ...

How can I change the transparency of a CSS background color using JavaScript?

I have a question about CSS: .class1 { background: #fff } Now, I need to achieve the following: .class2 { background: rgba(255,0,0,0.5) }; Is there a way to use JavaScript only to change the background property of .class1 and give it an opacity of 0.5? ...

Issue with useEffect causing a delay in updating the state value

I'm facing an issue with a component that displays the number of people who have liked a book. The problem is, I can't seem to consistently get the correct result in my states. Here's the code snippet: ///Fetching the book details cons ...

Preparing user context prior to executing controllers within AngularJS

I recently created an AngularJS application and integrated a REST API to fetch resources for the app. As part of the authentication process, I store the user's access token in a cookie. When the user reloads the page, I need to retrieve user informati ...

Are there any publicly accessible Content Delivery Networks that offer hosting for JSON2?

Everyone knows that popular tech giants like Google and Microsoft provide hosting for various javascript libraries on their CDNs (content distribution networks). However, one library missing from their collection is JSON2.js. Although I could upload JSON2 ...

JavaScript does not recognize Bootstrap classes

I am utilizing Bootstrap 5.3.0 and have included it through CDN links in my JS script. This is how I am injecting it using my js file within the existing website's DOM via a chrome extension named Scripty, which serves as a JS injector extension for c ...

Retrieving property values from an object across multiple levels based on property name

I have a complex object structure that contains price information at various levels. My goal is to retrieve all values from the Price property, regardless of their nesting within the object. var o = { Id: 1, Price: 10, Attribute: { Id: ...

AngularJS directive created for validation on blur

I am striving to replicate some of the features found in Angular 1.3.X for the app I am developing, with a particular focus on ensuring compatibility with IE 8. Unfortunately, this constraint means that I cannot utilize version 1.3.X. I have encountered di ...

Experience seamless transitions with Material UI when toggling a single button click

When looking at the examples in the Material UI Transitions documentation, I noticed that there are cases where a button triggers a transition. In my scenario, I have a button that triggers a state change and I want the previous data to transition out befo ...

Requesting for a template literal in TypeScript:

Having some trouble with my typescript code, it is giving me an error message regarding string concatenation, const content = senderDisplay + ', '+ moment(timestamp).format('YY/MM/DD')+' at ' + moment(timestamp).format(&apo ...

The information from the textarea and select option is not getting through to the email

Despite following suggestions, I am still unable to figure out why my form is not functioning properly. The form I have collects various information such as name, email, phone number, a select option, and a message in a textarea input. I dynamically change ...