Updating and eliminating text within an array of objects using Vue JS

My Axios request pulls in an array of objects named 'uniquecolors'. Here is what it looks like:

     mycolors 
      color: [GREEN, RED, BLUE, YELLOW, ORANGE,ORANGE,GREEN,]
      color: [GREEN, RED, BLUE, YELLOW, ORANGE,ORANGE,GREEN,]
      color: [GREEN, RED, BLUE ]
      color: [YELLOW, ORANGE]
      color: [GREEN, GREEN,GREEN,RED]
      color: [ORANGE,GREEN,ORANGE,GREEN,RED]`
  1. I want to retain only the colors 'RED' and 'GREEN' for each object

  2. I intend to substitute 'RED' with 'Crimson'

  3. I aim to swap 'GREEN' with 'Sage'

    `methods:
    ....
    
        const uniquecolorscationwithduplicates = uniquecolors
         .toString()
         .replace("RED", "Crimson")
         .replace("GREEN", "Sage")  
         .replace("YELLOW,", "")
         .split("|");``
    

The current result retains all original colors and appends 'Crimson' and 'Sage'. Thus it now displays 'GREEN,Sage,RED,Crimson,BLUE, YELLOW, ORANGE' without replacement.

What could be causing this?

In attempting to remove colors, I resorted to replacing them with blank strings. I realize this may not be ideal coding practice; any advice on better approaches would be appreciated.

Ultimately, I hope to alter all occurrences of colors during page rendering. Any guidance on how to achieve this would be welcomed.

Thank you in advance

Answer №1

Give this code a try utilizing the map and filter functions.

const mycolors = [
    {color: ['GREEN', 'RED', 'BLUE', 'YELLOW', 'ORANGE', 'ORANGE', 'GREEN']},
    {color: ['GREEN', 'RED', 'BLUE', 'YELLOW', 'ORANGE', 'ORANGE', 'GREEN']},
    {color: ['GREEN', 'RED', 'BLUE']},
    {color: ['YELLOW', 'ORANGE']},
    {color: ['GREEN', 'GREEN', 'GREEN', 'RED']},
    {color: ['ORANGE', 'GREEN', 'ORANGE', 'GREEN', 'RED']}
];

const colored = mycolors.map(({color}) => {
    let filtered = color.filter(col => col === 'RED' || col === 'GREEN')
        .map(el => {
            return el === 'RED' ? 'Crimson' : 'Sage';
        });
    return {color: filtered};
});

console.log(colored)

Answer №2

To accomplish this task, you can make use of JavaScript's Array.map(), Array.filter(), Array.join(), and String.replaceAll() methods.

See the code snippet below for a live demonstration:

const data = [{
  fruits: ['APPLE', 'BANANA', 'ORANGE', 'PINEAPPLE']
},{
  fruits: ['GRAPE', 'KIWI', 'PEACH']
},{
  fruits: ['STRAWBERRY', 'BLUEBERRY', 'RASPBERRY']
}];

const result = data.map(({ fruits }) => {
  const filteredFruits = fruits.filter(fruit => fruit === 'APPLE' || fruit === 'BANANA');
  const newObj = {
    fruits: filteredFruits.join().replaceAll('APPLE', 'Red Apple').replaceAll('BANANA', 'Yellow Banana').split(',')
  };
  return newObj;
});

console.log(result);

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

Empty initial value for first item in array using React hooks

My goal is to store an array that I retrieve from an API in a useState hook, but the first entry in my array always ends up empty. The initial array looks like this: (3) ["", "5ea5d29230778c1cd47e02dd", "5ea5d2f430778c1cd47e02de"] The actual data I recei ...

Complete Search with the press of Enter on the Auto Textbox

I have implemented an Ajax auto complete extender on a TextBox control. As the user begins typing, suggestive options are displayed below the input field based on data retrieved from a webservice call. When OnClientItemSelected="GetCode" is triggered, the ...

Innovative solution for detecting and replacing undefined object properties in Angular 2 with TypeScript

After encountering the issue of core.umd.js:3523 ORIGINAL EXCEPTION: Cannot read property 'fullName' of undefined I realized that the Exception stemmed from a Template trying to access a specific property: {{project.collaborators["0"]["fullN ...

Jasmine spies falsely report the calling of functions when they have not actually been called

Below is the code snippet I am currently working with: $scope.deleteJob = function(job) { SandboxService.deleteJob(job.id).then(res => { if (res.status == 200) { ngToast.success(); $scope.refreshApps(); } ...

Grab the source attribute of the <img> tag (identified by class) across numerous HTML pages

Here is an example: A website has the URL , where xxxx represents an integer between 1 and 1935. On each page, there may be an <img class="thumbnail" src="Images\Robots\{robotname}.png">. However, not all pages have th ...

Using Leaflet to make geojson XMLHttpRequests

Recently, I've been exploring the world of JavaScript and attempting to map around 2,200 data points in Leaflet. Despite following a helpful tutorial on pulling data from a geojson file and displaying it on a map, I can't seem to make it work wit ...

Is there a way in React JS to attempt a function multiple times using try/catch?

I wrote a function with try catch inside where I make a call to an API for a response. The response returns a Result object with some data. Occasionally, I need to retry the function if certain conditions are met, such as having no name but having a bundle ...

JQuery is failing to parse JSON data

I've written a script to fetch data and display it in an HTML table. Here is the script: $('#search_filter_button').click(function (e) { e.preventDefault(); // Prevent form submission var county = $('#filter_county').val() ...

Exclude basic authentication for a specific route

Using node, express and connect for a simple app with basic HTTP auth implemented. The code snippet below shows part of the implementation: var express = require('express'), connect = require('connect'); app.configure = function(){ ...

How to activate select only when specific options are chosen using jQuery

I am working on a form that has 1 select element disabled, with 4 options. I am looking to implement a jQuery function that will perform the following actions: If OPTION #1 is clicked, it should check if any other options are selected and reset them (eras ...

What is the best way to fix multiple dropdown menus opening simultaneously in Vue.js?

I am working on an application that generates todo lists for tasks. These lists can be edited and deleted. I am trying to implement a dropdown menu in each list to provide options for updating or deleting the list individually. However, when I click on the ...

Reversing the sequence of code in JavaScript - react native

I'm currently working on tracking the number of times a button is pressed within one second. For the most part, it's functioning correctly as it tracks and displays the count. The issue arises when it displays the button press count from the pr ...

What is the reason behind the content of a div tag not hiding while the content of a p tag does

<html> <head> <title>How to make a div content disappear when clicked?</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <scrip ...

load a particular section of another website into my own div

Similar Question: Ways to bypass the same-origin policy I've been looking for a way to load a specific div from another website using this code. Can anyone provide an example of how to do this on jsfiddle? $.ajax({ url: 'http://somethin ...

Secure your website against XSS attacks with DOMPurify

Currently I am working on resolving a cross-site scripting (XSS) vulnerability using DOMPurify. The issue lies in the URL provided below: https://stage-xyzmysite.com/login/?rUrl=javascript:alert('hi'). In order to create a proof of concept, I am ...

Navigating through two nested arrays in JavaScript to access an object

Having difficulty extracting the nested car values using JavaScript (lodash). Take a look at the JSON data below: { "cars":[ { "nestedCars":[ { "car":"Truck", "color" ...

Placing a div tag directly beneath another div tag

Imagine you have a div element with the class name divstudent, let's call this one div1. Now, you want to dynamically create another div element below div1, but outside of it using JavaScript. How can you achieve this? "div1" <div class="divstuden ...

Launching a React project using the terminal - my step-by-step process

I'm attempting to initiate a new react-app utilizing the command npx create-react-app <app name> as shown below: npx create-react-app new-app However, after downloading, it seems to be stuck. It's not progressing at all. I've even rei ...

Is there a way to modify the package version with yarn, either upgrading or downgrading?

Is there a way to downgrade the version of a package using yarn's "dependencies" feature? ...

jQuery breaks when working with ASP.NET forms

Essentially, it appears that using an ASP.NET page with the <form runat=server> tag can cause some jQuery scripts to break. To illustrate this issue, consider the following scenario: You have a simple webpage with only a checkbox, like so: <inpu ...