Is there a way to compare a particular JSON value to the values in an array and determine if they are similar? If so, how can I update the JSON value with the array value

My inventory of wholesalers looks like this:

const wholesalers = [
  "B536 - T QUALITY LTD",
];

I also have a collection of JSON objects as shown below:

{
  'Preferred Wholesaler': 'T-Quality'
}, 
{
  'Preferred Wholesaler': 'T Quality'
},

I need help figuring out how to match the value of 'Preferred Wholesaler' in the JSON object with one of the values in the array. Once matched, I want to update the JSON object with the corresponding value from the array, for example: 'Preferred Wholesaler': 'B536 - T QUALITY LTD'.

This is what I have tried so far:

// Ignoring the first 7 characters of the wholesaler and removing " LTD" from the end:
var newWholesalers = wholesalers.map(wholesaler => {
  return wholesaler.substring(7).replace(" LTD", "")
});

// Processing JSON Data
var newRecords = data.map(record => {

  record["Preferred Wholesaler"] = record["Preferred Wholesaler"].toUpperCase()

  // Checking if preferred wholesaler exists in the array
  // If yes, updating with 'True', else setting it as 'False'
  if (newWholesalers.includes(record["Preferred Wholesaler"])) {
    return {
      ...record,
      ["Preferred Wholesaler"]: 'True'
    }
  } else {
    return {
      ...record,
      ["Preferred Wholesaler"]: 'False'
    }
  }
});

I am looking for a solution to make the includes() function return the matched value instead of true/false. Any suggestions?

Answer №1

Perhaps this solution could provide some guidance for you...

const suppliers = [
  "ACME Corporation",
  "Global Solutions Ltd",
];

var myItems = [
  {
    'Preferred Supplier': 'ACME'
  },
  {
    'Preferred Supplier': 'Global Solutions'
  },
]

myItems.forEach(function(product, index) {
  suppliers.forEach(function(supplier, index) {
    if (supplier.replace(/-/g, ' ').toLowerCase().includes(product['Preferred Supplier'].replace(/-/g, ' ').toLowerCase())) {
      product['Preferred Supplier'] = supplier
    }
  });
  
});

console.log(myItems);

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

displaying information in table cells with jquery

Is there a way to display a table inside a td element with an on-click function without showing all tables in the same column when the function is triggered? I want the table to be shown only for the specific td that was clicked. $(document).ready(funct ...

Leverage the power of EJS and Node JS by incorporating node modules into

I am having trouble importing my datetimepicker JavaScript and style sheet into my EJS file. Unfortunately, the CSS and JS files are not rendering properly when I run the code. Below is how my code is structured: In the EJS file: <html> <meta n ...

Securing client-side code with AngularJS for enhanced security

It's a known fact that once browsers have downloaded frontend files, there's no way to hide code from the client. However, I've heard that clients can debug JavaScript code, add breakpoints, skip code lines (especially security checks), and ...

Enhance your application by utilizing additional hooks in the Context API

I'm exploring API and react hooks and have a query related to dispatching API fetch to ContextAPI component. Is there a way to consolidate all useState hooks into a single ContextAPI component? The objective is code refactoring by breaking it down int ...

What could be causing the 404 error I'm receiving for this specific URL?

Can someone explain why I keep encountering a 404 error when I type \book into the URL bar? Below is the code I am currently using: var express = require('express'), app = express(), chalk = require('chalk'), debug = ...

How can you permit parameters for a complete jsonb PostgreSQL column in a controller in Rails 5?

I attempted to utilize the recommended example from github. It can also be found in responses like this one for Rails 4. I gave it a shot in Rails 5.0.1 and all I got was an empty hash {} stored in the database: def proposal_params params.require(:prop ...

The initial render of Keen-slider in NextJS can sometimes encounter difficulties when using server-side rendering

While incorporating the keen-slider library v5.4.0 into my nextJS project with TypeScript, I encountered a peculiar issue. The error arises when the keen-slider is initially loaded for the first time, resulting in mismatched transform types causing items ...

Is there a way to ensure that the vertical scrollbar remains visible within the viewport even when the horizontal content is overflowing?

On my webpage, I have multiple lists with separate headers at the top. The number of lists is dynamic and can overflow horizontally. When scrolling horizontally (X-scrolling), the entire page moves. However, when scrolling vertically within the lists, I wa ...

"Enhancing user experience: dynamically adding rows using a combo of jquery, ajax, and php

This is the layout of my table. Here is the result I'm getting. Below is the code snippet: <table width="100%" id="controltable" border="1"> <tr> <th> Product Name </th> <th> Product Pri ...

Facing Problem with Angular PUT Request - "Missing required request body"

I'm encountering a problem with my Angular application when attempting to send a PUT request to the server. The error message I receive reads "Required request body is missing." Below is a snippet of the code that is relevant: Within the Child Compo ...

What is the best way to access all of a class's properties in JavaScript?

Is there a way to retrieve all the properties of a class using JavaScript? For example, if I have a class like this: .menu { color: black; width: 10px; } How can I extract "color: black; width: 10px;" as a string using JavaScript? Thanks in advance! ...

What potential issues arise from utilizing useRef alongside useSelector?

Although I have the capability to access the store by using thunks and/or global stores, I avoid binding my component to the Redux store. This is because the component will be utilized with various stores both inside and outside of the project. The compone ...

Newly included JavaScript file displays on view page, but triggers a 404 error when attempting to open

Once I implemented the following code in the child theme's function.php file: add_action('wp_enqueue_scripts', 'js_files'); function js_files() { wp_register_script('ajax_call_mkto', get_template_directory_uri() . ' ...

Obtain the Text Content from a Knockout Dropdown Menu

Currently, I am facing an issue with extracting the text value of a selected option from a dropdown menu on my webpage. The dropdown contains various image categories and is defined as follows: <select class="form-control" data-bind="options: imageCate ...

Encountering an Error with JsonRpcProvider while deploying a contract or attempting to run a node

An error has occurred: Error: ERROR processing skip func of /home/dylan/hh-fcc/hardhat-smartcontract-lottery-fcc/deploy/00-deploy-mocks.js: TypeError: Cannot read properties of undefined (reading 'JsonRpcProvider') While following the freecodeca ...

Is there a way to reset the input text in VueJS once a button has been clicked?

Is there a way to make the text in the input box clear once the enter button is pressed and the addTask function is executed to add the task to the list? I attempted to use document.getElementById("inp").innerHTML = "" but it didn't work. Any suggesti ...

Having trouble connecting a JavaScript file from my local directory to an HTML document. However, when I try to access it in the browser, I keep getting

Currently, I am attempting to connect a javascript file to my html document. Following the directions at this link, I am trying to enable the selection of multiple dates from a calendar as input in a form. The instructions mention that I need to include ...

Acquire the worth of the <MenuItem> element from React's mui/material library

I am attempting to retrieve the value of the selected item listed below: Here is my attempt at logging this information: console.log("Event: ", event.currentTarget); Output: <li class="MuiButtonBase-root MuiMenuItem-root MuiMenuItem-gut ...

Converting Textbox values into an array

Currently, I am facing a challenge with multiple Textboxes. My goal is to iterate through them, check if they have a value, and then store that value in an array. Specifically, the Textboxes are named txtText1, txtText2, and so on up to txtText12. This is ...

Angular route unable to detect Passport User Session

The navigation bar in the header features buttons for Register, Login, and Become a Seller. Upon user login, it displays logout and view profile buttons. This functionality is operational on all routes except one, causing a client-side error. user not def ...