Home > Net >  Replace and remove text in Vue JS array of objects
Replace and remove text in Vue JS array of objects

Time:11-15

I have an array of objects which I pull in via an Axios request called 'uniquecolors'. It looks like this:

     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 would like to remove all colors apart from 'RED' and 'GREEN' for each object

  2. I would like to replace 'RED' with 'Crimson'

  3. I would like to replace 'GREEN' with 'Sage'

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

This actually keeps all the colors but adds on Crimson and Sage. So it displays 'GREEN,Sage,RED,Crimson,BLUE, YELLOW, ORANGE' instead of replacing.

Why would that be?

To remove I have been replacing with a blank string. I know this is a bad way to code it but Im not sure how else to do this.

Ideally I'd like to change all instances of the colors when the page renders so any pointers would be helpful.

Thanks in advance

CodePudding user response:

try this code, u can use map and filter.

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)

CodePudding user response:

You can simply achieve this by using Array.map(), Array.filter(), Array.join() and String.replaceAll() methods of JavaScript.

Live Demo :

const arr = [{
  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 res = arr.map(({ color }) => {
  const filteredColor = color.filter(c => c === 'GREEN' || c === 'RED');
  const obj = {
    color: filteredColor.join().replaceAll('RED', 'Crimson').replaceAll('GREEN', 'Sage').split(',')
  };
  return obj;
});

console.log(res);

  • Related