I have a JS object array as :
[ { workoutName: 'Farmers Walk' }, { workoutName: 'BW Lateral Lunge Hop (Left)' }, { workoutName: 'Dumbbell Cross Chops (Right)' }, { workoutName: 'BW Oblique Jumping Jacks' }, { workoutName: 'BW Wide Press Parallel' }, { workoutName: 'BW Single Leg Lunge Jump (Left)' }, { workoutName: 'BW Jump Squat' }, { workoutName: 'BW Squat to Toe Tap' } ]
I’m saving the objects that are (Left) & (Right) to a new array.
let substrL = 'Left' let substrR = 'Right' let remaining = [] results.find((o) => { if (o.workoutName.includes (substrR) || o.workoutName.includes (substrL)) //results.map(obj => ({ workoutName: obj.workoutName.replace('Left','Right')})) remaining.push(o) });
What I cannot do is, I’m trying to replace the partial string of the remaining[] array.
in this example , the results are is
[ { workoutName: 'BW Lateral Lunge Hop (Left)' }, { workoutName: 'Dumbbell Cross Chops (Right)' }, { workoutName: 'BW Single Leg Lunge Jump (Left)' } ]
what I would like to do / the expected outcome is to have the opposite of the results arr.
[ { workoutName: 'BW Lateral Lunge Hop (Left)' }, //workoutName: 'BW Lateral Lunge Hop (Right)' { workoutName: 'Dumbbell Cross Chops (Right)' },//workoutName: 'Dumbbell Cross Chops (Left)' { workoutName: 'BW Single Leg Lunge Jump (Left)' }//workoutName: 'BW Single Leg Lunge Jump (Right)' ]
Advertisement
Answer
You did everything and just needed the opposite of what is present. Without affecting the original object, you can use the spread operator to store the object, then check what type of content is stored within the parentheses, and alter them:
var results = [ { workoutName: 'Farmers Walk' }, { workoutName: 'BW Lateral Lunge Hop (Left)' }, { workoutName: 'Dumbbell Cross Chops (Right)' }, { workoutName: 'BW Oblique Jumping Jacks' }, { workoutName: 'BW Wide Press Parallel' }, { workoutName: 'BW Single Leg Lunge Jump (Left)' }, { workoutName: 'BW Jump Squat' }, { workoutName: 'BW Squat to Toe Tap' } ] let substrL = 'Left' let substrR = 'Right' let remaining = [] results.find((o) => { if (o.workoutName.includes(substrR) || o.workoutName.includes(substrL)) { let data = { ...o } if (o.workoutName.includes(substrR)) data.workoutName = o.workoutName.replace(substrR, substrL) else data.workoutName = o.workoutName.replace(substrL, substrR) remaining.push(data) } }); console.log(remaining)