Transform a JavaScript array using key value pairs sourced from a JSON document

I am currently working on developing a feature to detect and flag inappropriate comments within my application.

One approach I am taking involves splitting the comment into an array of strings. I am now looking to implement a JavaScript function that can assign a numerical value to each array item based on predefined key-value pairs stored in a JSON object. If a matching key is not found, the item should be replaced with a 0.

The ultimate goal is to sum up all the numerical values in the final array to calculate a comment score.

For instance, given the initial array:

["Bad", "reallyBad", "Good", "Neutral", "Good"]

I plan to compare it against a JSON object with key-value pairs like:

{
    "reallyBad": -10,
    "Bad": -5,
    "Good": 5,
    "reallyGood": 10
}

Following these mappings, the updated array should look like this:

[-5, -10, 5, 0, 5]

If you have any insights on how to efficiently convert strings based on key-value pairs, I would greatly appreciate your guidance.

Any assistance you can provide would be immensely valuable.

Answer №1

To efficiently process an array, you can utilize the `.map()` method. This function iterates over each item in the array, allowing you to apply a specific operation and obtain a desired output. In this case, you can use each string within the array as a key to retrieve the corresponding value from the ratings object.

const array = ["Bad", "reallyBad", "Good", "Neutral", "Good"];

const ratings = {
    "reallyBad": -10,
    "Bad": -5,
    "Good": 5,
    "reallyGood": 10
};

const ratingsArray = array.map(item => ratings[item] || 0);

console.log(ratingsArray);

Answer №2

Simply assign values to the object properties or set a default value for Neutral.

var array = ["Bad", "reallyBad", "Good", "Neutral", "Good"],
    weights = { reallyBad: -10, Bad: -5, Good: 5, reallyGood: 10 },
    result = array.map(w => weights[w] || 0);
    
console.log(result);

Answer №3

If you want to transform an array using the Array.map() method, you can do it easily.

Give this a shot:

var array = ["Apple", "Banana", "Cherry", "Date", "Elderberry"];
var object = {
    "Apple": "A",
    "Banana": "B",
    "Cherry": "C",
    "Date": "D",
    "Elderberry": "E"
};

var transformedArray = array.map((item) => object[item] || "Unknown");

console.log(transformedArray);

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

Using JSON Object for Default Selection in an Angular Dropdown Menu

Here is some code I have that fills in a specific select item on a webpage: <select ng-model="activity.selectedParent" ng-options="parent as parent.title for parent in parents track by parent._id"></select><br> I'm curious if there ...

problem with saving session data

I am attempting to access data from another page using session storage. On my initial page, named home.html function go_to_faq(qnum){ window.open('FAQ.html', '_blank'); sessionStorage.setItem('key2', qnum); } <a s ...

Error occurs when trying to retrieve data from a nested JSON feed

I'm still getting the hang of JSON feeds and Swift 4. My current struggle involves extracting data from a nested JSON feed. I'm not entirely confident if I'm calling the array correctly in my do statement. On top of that, whenever I try to b ...

Generate projectiles within a game periodically

I've created a game that features a main character and enemy soldiers who shoot back. I'm facing an issue where only one enemy soldier shoots at intervals, even though I initially used setInterval for both of them. Any suggestions on how to fix t ...

Issues with simple jquery and javascript: unable to add the class ".has-error" and onclick event not properly defined

Currently, I am working with jQuery version 2.1.4 and JavaScript to implement a straightforward form validation using Bootstrap. During this process, I have encountered three peculiar issues. While I am confident that my jQuery code is properly functi ...

What is the best way to extract plain text with JQuery?

I found this Html code snippet: <div class="form-group row"> <label id="lb_size" class="col-lg-3 col-form-label"> <span class="must-have">****</span> Size </label> </div> My goal is to ext ...

Creating a canvas with multiple label introductions can be achieved by following these

I am looking to group labels and sublabels on the x-axis of a canvas component. Currently, I only have sublabels like: RTI_0, RTI_1... I would like to add labels to these sublabels like: RTI = {RTI_0,RTI_1,RTI_2] BB = {BB_0, BB_1,BB_2,BB_3] <div cla ...

Taking a Symfony approach to handling actions that return a JSON response

Utilizing PHP and CURL, I am retrieving data from a server in one of my actions and then returning the data in JSON format. The code for my action is as follows: public function executeTest(sfWebRequest $request) { $json = $this->getServerResponse ...

Exploring AngularJS's capabilities with asynchronous tasks

I am in the process of developing a simple app using AngularJS. One of the key functionalities I am working on is removing items from a list. To achieve this, I have created the following code snippet: $scope.removeItem = function(item) { var toRemove = ...

Using the React Native useState hook to modify an array within an object of arrays

How can I effectively use the useState hook to modify an array within an array of objects that relies on a specific array index? The desired data structure looks like this: foodData = [ { foodId: 'fdsafsdafsa', fruitsArray: ['ban ...

Can one utilize Javascript to write in plain text format?

Currently, using JavaScript I have a plain text containing data that is displayed within my form tags. Everything is functioning correctly, but now I need to update the values inside the code of my form tags in order for the changes to also be reflected in ...

Are current web browsers able to block the code "<a href="javascript:window.open....?

I am looking to create a pop-up window for sharing on Facebook. The best way to achieve this is by using javascript to pop up a small window with a width of 400 pixels and a height of 200 pixels. Will pop-up blockers in Chrome, IE, or Google block this f ...

Guidelines for parsing JSON data into a nested class with JSON.net

Here is my JSON data: {"customer":[{"phone":"9868133331"},{"phone":"9971714514"}],"message":[{"type":"reminder"},{"type":"reminder"}]} This JSON is structured as follows: { "customer": [ { "phone": "9868133331" }, { "phone": "9 ...

Tips for simplifying validation in Java without using multiple if-else statements

I'm facing a challenge with my code structure that involves multiple if-else statements for different input values. In order to optimize my code, I am looking to create a single function to handle all if else logic. The input request is in JSONObject ...

What could be causing my Mocha reporter to duplicate test reports?

I've created a custom reporter called doc-output.js based on the doc reporter. /** * Module dependencies. */ var Base = require('./base') , utils = require('../utils'); /** * Expose `Doc`. */ exports = module.exports = ...

Leaving the pipeline of route-specific middleware in Express/Node.js

My implementation involves a sequence of "route specific middleware" for this particular route: var express = require('express'); var server = express(); var mw1 = function(req, resp, next) { //perform actions if (suc ...

eliminating various arrays within a two-dimensional array

I need help with a web application that is designed to handle large 2D arrays. Sometimes the arrays look like this: var multiArray = [["","","",""],[1,2,3],["hello","dog","cat"],["","","",""]]; I am looking to create a function that will remove any array ...

What is the best way to utilize an audioStream provided by the Amazon Lex SDK during the process of recognizing a spoken phrase?

I have successfully built a chatbot using Amazon Lex and integrated it with a Node.js Rest API by following the official documentation. After sending a RecognizeUtteranceCommand, I am receiving an audioStream in the response. Now, the main challenge I&ap ...

Click on every link to reveal a hidden div

When I click on and select the first link in the mainPart, I want to automatically select the first subLink div in the secondPart while hiding the other subLink classes. This sequence should be maintained: when the second link is selected, the second sub ...

Error: You can't use the 'await' keyword in this context

I encountered a strange issue while using a CLI that reads the capacitor.config.ts file. Every time the CLI reads the file, it throws a "ReferenceError: await is not defined" error. Interestingly, I faced a similar error with Vite in the past but cannot ...