Find the corresponding value in an array by matching it with a key from an Object, and then replace the

In my coding challenge, I am trying to find a way to match the keys from an Object to elements in an array and replace the matching elements in the array with the corresponding key values.

Here is what I currently have:

Arr = [ 'Saturday', 'niCCCght', 'plans,', 'CCC' ]

Obj = { "AAA": "BBB", "CCC": "DDD", "EEE": "FFF" }

After running my code, I am getting the following output:

[ 
  [ 'Saturday', 'Saturday', 'Saturday' ],
  [ 'niCCCght', 'niCCCght', 'niCCCght' ],
  [ 'plans,', 'plans,', 'plans,' ],
  [ 'CCC', 'DDD', 'CCC' ] 
]

But what I really want is this desired output:

[ 'Saturday', 'niCCCght', 'plans,', 'DDD' ]

Any help on achieving this would be greatly appreciated. Thank you!

function test() {
  let Arr = [ 'Saturday', 'niCCCght', 'plans,', 'CCC' ];

  const Obj = {"AAA":"BBB", "CCC":"DDD","EEE":"FFF"};
  
  const Z = Arr.map(v => matchedKey(Obj,v))

  console.log(Z);
}
let matchedKey = (Obj,str) => Object.keys(Obj).map(key => key===str ? Obj[key]: str);

Answer №1

Your approach seems to be overcomplicated. A simpler way to achieve the same result is by using the map() function to iterate over the input array and search for a matching property name in the object. If a match is found, return the corresponding property value; otherwise, return the original value:

const arr = ['Saturday', 'niCCCght', 'plans,', 'CCC']
const obj = { "AAA": "BBB", "CCC": "DDD", "EEE": "FFF" }

var output = arr.map(v => obj[v] ?? v);
console.log(output);

Another option is to use hasOwnProperty(), which provides a more explicit indication of the logic being applied. Both methods will yield the same result:

var output = arr.map(v => obj.hasOwnProperty(v) ? obj[v] : v);

Answer №2

Iterating through all the keys in the object, replacing the matching indexes with the corresponding values.

function updateArray() {
  var arr = ['Saturday', 'niCCCght', 'plans,', 'CCC'];
  const obj = { "AAA": "BBB", "CCC": "DDD", "EEE": "FFF" };
  Object.keys(obj).forEach(key => {
    let idx = arr.indexOf(key)
    if (~idx) arr[idx] = obj[key];
  })
  Logger.log(JSON.stringify(arr))
}

Execution log
1:24:36 PM  Notice  Execution started
1:24:30 PM  Info    ["Saturday","niCCCght","plans,","DDD"]
1:24:38 PM  Notice  Execution completed

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

Ways to incorporate a php file based on the user's selection

I have numerous div elements, possibly a dozen or two, such as... <div class="mydivs" id="firstdiv"></div> <div class="mydivs" id="seconddiv"></div> <div class="mydivs" id="thirddiv"></div> <div class="mydivs" id="fo ...

"Using Bootstrap's toast feature repositions every element on the

I am working on a website project and encountering an issue with a bootstrap toast. The toast currently appears in the top right corner, but I would like it to display above the carousel without affecting the layout. Instead, when the toast appears, it shi ...

JavaScript, JQuery, and the Observer Design Pattern

Currently, I am in the process of developing a third-party application specifically for certain websites using Jquery. Lately, I have incorporated rx.Observable into my project. However, grasping the utilization of this new JS library has proven to be qui ...

Optimal code structuring for a javascript plugin

Hey there, I came across some intriguing posts on this topic, but I believe it's a very personal question that requires a tailored answer. So, I'm reaching out to ask you: what is the most effective way to organize my code for a JavaScript plugin ...

Looking for a Plugin that Can Responsively Display Images in a Vertical Layout - Does One Exist using Jquery

Looking for a gallery slider plugin that is responsive both horizontally and vertically. Have tried Flexslider1/2, Galleria, and others but they do not adjust to vertical resizing. Changing the CSS did not help. If you resize the browser horizontally with ...

Unable to transform object into a primitive value using imported JSON data

https://i.sstatic.net/HcY5M.png I am currently working on creating a Vuetify component dynamically within a Nuxt project, as discussed in this Stack Overflow thread (Using different text values with Vuetify component). To achieve this, I am importing and ...

Tips on positioning a div based on the screen dimensions

In my table, there is an icon that reveals a chart as a popup when hovered over. This div is where the chart is displayed: <div id="chart-outer" style="@style" class="popup-chart close"> <h2 id="charttitle&q ...

Choosing information from a CSV file

I need to retrieve data from a CSV file and here is the code I have written: var filenamecsv="D://Data.csv"; adoConn1.Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=d:\; Extended Properties='text;HDR=Yes;FMT=Delimited';") ...

The post processing effect in Three.js does not support FXAA when SSAO is activated

I am having trouble getting SSAO and FXAA effects to work together in this simple test scene. Enabling SSAO works fine, but when I also enable FXAA, the render turns black. In the provided fiddle, if you uncomment composer.addPass(FXAA_effect); you will s ...

Text field auto-saving within an iFrame using localStorage is not functioning as expected

My goal is to create a rich text editor with an autosave feature using an iframe. Although each code part works individually, I am struggling to combine them effectively. View LIVEDEMO This graphic illustrates what I aim to accomplish: The editable iFram ...

Ionic: Error - Unable to access the 'ready' property of an undefined object

I keep encountering this error message: TypeError: Cannot read property 'ready' of undefined Here is the snippet of my code: angular.module('app', ['ionic', 'app.controllers', 'app.routes', 'app.dir ...

Cannot locate AngularJS + Typescript controller

I'm encountering an error while attempting to integrate TypeScript with AngularJS. The issue I'm facing is: Error: [$controller:ctrlreg] The controller named 'MyController' has not been registered Does anyone have any insights on what ...

Exploring (nested) data structures in JavaScript

I'm struggling to understand if my issue lies in how I am organizing my array or in how I am accessing it. The idea is simple: I want to have an array of car makes and models that I can access for display purposes. const carBrands = [ { Audi: { ...

Design a hover zone that allows for interaction without disrupting click events

I am looking to create a tooltip box that appears when hovering over an element, and I want the tooltip to only disappear when the user's mouse exits a specific custom hover area outlined by a vector graphic. My current implementation is working, but ...

When attempting to modify styles in IE10, I consistently encounter an error message stating "Unable to evaluate expression."

Below is a JavaScript function I have created to hide an HTML tag: function hideObject(objectId) { var obj = document.getElementById(objectId); if (obj) { obj.style.display = "none"; } } I encountered a strange issue when using this ...

Ensuring accurate data entry through form validation within a table format

I'm working with a textbox that is part of a table column. My goal is to make sure the entire column is not empty when the Ok button is clicked. If you have any suggestions on how I can achieve this, please let me know. var formatTableMandatoryVa ...

Exploring an alternative perspective on successful login in angular.js

Today was the beginning of my project to convert a website to angular.js. The main page is served by index.html and includes ng-view for other views such as login and signup. Working closely with a backend developer, I have successfully integrated a rest c ...

Array insertion is not supported by Node MSSQL

I am trying to insert multiple rows at once using an array of data. Here is how my array is structured: [ [ '1234' ], [ '5678' ], [ '9123' ]... ] And here is the query code I am using: const sql = require('mssql&a ...

unable to successfully npm install canvas

For my GitHub repository, please visit here This project was actively developed until November of last year, after which I did not commit any changes. Today, I attempted to run the project again but encountered the following error. My current system versi ...

The second guard in Angular 5 (also known as Angular 2+) does not pause to allow the first guard to complete an HTTP request

In my application, I have implemented two guards - AuthGuard for logged in users and AdminGuard for admins. The issue arises when trying to access a route that requires both guards. The problem is that the AdminGuard does not wait for the AuthGuard to fini ...