Is there a way to swap out values in a JavaScript Object for new ones?

I need to update the initial values of myObject with new names:

let myObject = 
  [ { name: 'X0', values: 'FALSE,TRUE'      } 
  , { name: 'X1', values: 'NORMAL,LOW,HIGH' } 
  , { name: 'X2', values: 'HIGH,NORMAL,LOW' } 
  , { name: 'X3', values: 'FALSE,TRUE'      } 
  ]     

I have two arrays: arr1 contains all unique values from myObject, and arr2 has the corresponding renamed values that should replace the original ones in myObject. They are already in the correct order:
For example, FALSE should be replaced with JDIFS, LOW with T9SQK, and so on.

let arr1 = ['FALSE', 'TRUE',  'NORMAL', 'LOW',   'HIGH'  ]
let arr2 = ['JDIFS', 'CZ899', 'YVI0T',  'T9WQK', '0XCH7' ]

Expected Output :

let expected = 
  [ { name: 'X0', values: 'JDIFS,CZ899'        } 
  , { name: 'X1', values: 'YVIOT,TW9WQK,0XCH7' } 
  , { name: 'X2', values: '0XCH7,YVIOT,T9WQK'  } 
  , { name: 'X3', values: 'JDIFS,CZ899'        } 
  ] 

I want to iterate over the object like this:

let second_column = myObject["columns"][1] 
for (let i=0; i< myObject.length; i++) {
  let tran = myObject[i][second_column].split(',') 
  // then perform the replacement using the two arrays, or by using the replace method
}

Answer №1

Give this a shot:

let data = [
  { title: 'X0', options: 'FALSE,TRUE' },
  { title: 'X1', options: 'NORMAL,LOW,HIGH' },
  { title: 'X2', options: 'HIGH,NORMAL,LOW' },
  { title: 'X3', options: 'FALSE,TRUE' },
];

const options1 = ['FALSE', 'TRUE', 'NORMAL', 'LOW', 'HIGH'];
const options2 = ['JDIFS', 'CZ899', 'YVI0T', 'T9WQK', '0XCH7'];

for (let i = 0; i < data.length; i++) {
  let transformed = data[i].options;
  for (let j = 0; j < options1.length; j++) {
    transformed = transformed.replace(options1[j], options2[j]);
  }
  data[i].options = transformed;
}

console.log("RESULT:", data);

Answer №2

Here is a code snippet that you can experiment with:

const myObject = [{"name":"X0","values":"FALSE,TRUE"},{"name":"X1","values":"NORMAL,LOW,HIGH"},{"name":"X2","values":"HIGH,NORMAL,LOW"},{"name":"X3","values":"FALSE,TRUE"}];
const arr1 = ["FALSE", "TRUE", "NORMAL", "LOW", "HIGH"];
const arr2 = ["JDIFS", "CZ899", "YVI0T", "T9WQK", "0XCH7"]
const result = myObject.map( i => {
   const data = i.values.split(',').map(val => arr2[arr1.indexOf(val)]);
   return {
    ...i,
    values: data.join(',')
   }
})
console.log(result)

i.values.split(','): "FALSE,TRUE" => ["FALSE","TRUE"]

arr2[arr1.indexOf(val)]: retrieve value using index position

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

Looking for assistance in determining a solution for progress bar implementation

Currently, I am developing a simple application using web technologies like HTML, CSS, and jQuery Mobile. This app enables me to create goals and save them to a listview using the <li> element. Every <li> representing a goal will have an assoc ...

Can you explain why the .js code is causing such high CPU usage in popular video players?

Why is the .js code running continuously even when the video is paused and there is no user interaction? I observed this phenomenon on a Windows 10 Atom Tablet, particularly when in energy-saving mode. The CPU usage for video playback and decoding almost ...

Challenge encountered while implementing a countdown using a for loop in a node.js application

I've been struggling with the following code and despite trying everything, I can't seem to find a solution. Hopefully, someone out there can lend me a hand. Currently, the code runs fRoll.roll, enters a FOR loop, initiates the countdown of the ...

Animating a dotted border path in SVG for a progress bar effect

I am attempting to create an animation for a dotted SVG circle that resembles a progress bar, where it fills itself over a duration of 3 seconds. However, I am facing difficulties in achieving this effect with the dotted border. The current code I have doe ...

A guide to retrieving JSON data with Javascript

I'm in the process of building a small website for weather forecasting. However, I've encountered an issue when trying to retrieve JSON data from accuWeather - I'm not getting any response. I've double-checked my request and it seems to ...

Styling the active selection in nav class with bold attribute in Bootstrap/AngularJs

How can I apply the bold attribute to the currently selected nav bar item? <ul class="nav"> <li role="presentation" ng-repeate="item in items" ng-class="{'active':navLink == item.header}"> </li> &l ...

Associating the object key and value with distinct attributes within the component

person = {name: 'Alice', age: '19', weight: 52} I'm looking to display both the keys and values from the object in one label and input field respectively. I attempted using Object.entries, but couldn't figure out how to sepa ...

The function io.sockets.in(roomName) does not seem to be properly listening for myEvent after joining the

I am looking to dynamically create rooms based on incoming requests from the front end. I found guidance in this gist. My goal is for a specific room to listen for events and communicate with other members within that room. However, I am experiencing an i ...

What is the best method for selecting only files (excluding folders) in Gulp?

I have a gulpfile where I am injecting files into an appcache manifest in this manner: var cachedFiles = gulp.src('**', {read: false, cwd: 'build'}); gulp.src('src/*.appcache', {base: 'src'}) .pipe($.inject(cachedF ...

Looking through a Json file and retrieving data with the help of Javascript

I am currently working on developing a dictionary application for FirefoxOS using JavaScript. The structure of my JSON file is as follows: [ {"id":"3784","word":"Ajar","type":"adv.","descr":" Slightly turned or opened; as, the door was standing ajar.","tr ...

Managing the state of dynamically generated tabs within a NextJS application

Looking to develop a web app in Next.js that includes tabs components. The goal is to manage various entities within each tab, such as utilizing a search bar to select different products. Upon selecting a product, a new tab will be generated with the produ ...

Is there any need for transpiling .ts files to .js when Node is capable of running .ts files directly?

If you are using node version 12, try running the following command: node hello.ts I'm curious about the purpose of installing typescript globally with npm: npm install -g typescript After that, compiling your TypeScript file to JavaScript with: ...

The ancient oracle of Delphi and the modern login portal of Microsoft

I need to login to a site that utilizes . To streamline the process for end-users, I want to store credentials in an .ini file and inject them into a two-stage JavaScript online prompt. Is there a way to have Delphi run a program with a browser that auto ...

Unable to authenticate with Firebase using ReactJS

I am currently working on developing a basic registration and login system using firebase authentication. However, I am facing an issue where the user appears to be saved when I restart the site in console.log, but the application redirects them back to th ...

The occurrence of the "contextmenu" event can cause disruption to the execution of a function triggered by the "onmousemove" event

Currently in the process of developing a Vue application utilizing a Pinia store system. Within my BoxView.vue component, I have created a grid layout with draggable elements that have flip functionality implemented within the BoxItem.vue component. Spec ...

Creating a React functional component that updates state when a specific window breakpoint is reached

Having an issue with my code when it hits the 960px breakpoint. Instead of triggering once, it's firing multiple times causing unexpected behavior. Can someone help me troubleshoot this problem? const mediaQuery = '(max-width: 960px)'; con ...

Unable to access a value from an object in Node.JS/MongoDB platform

I'm seeking assistance with my NodeJs project. The issue I am facing involves checking the seller's name and setting the newOrder.support to match the seller's support internally. Despite logging the correct value within the findOne() func ...

What is the technique to transfer the value from collection_select to the onchange method in Rails?

In my task, I need to extract the selected value from the collection_select drop-down menu and pass it to an onchange function. However, when I access the "name" attribute, the printed value is source[index]. Instead, I want to retrieve the actual value ...

Refresh website-wide variables after a post has been made

Within my index.js file, I am rendering a page with global variables. router.get('/index', function(req, res, next) { res.render('index', { title: 'RLH', countNumber: countNumber, countReleased: countReleased, coun ...

Send the parameter to the compile method within the directive

I am currently working on creating a generic field and utilizing a directive for it. In my HTML code, I have defined the following: <div def-field="name"></div> <div def-field="surname"></div> <div def-field="children"></d ...