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
Source:stackexchange.com