[Vuejs]-Replace and remove text in Vue JS array of objects

0๐Ÿ‘

โœ…

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);
๐Ÿ‘คDebug Diva

1๐Ÿ‘

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)
๐Ÿ‘คBuild For Dev

Leave a comment