I have a plainText object. I also have an array of objects. In that array of objects, each object contains offset and length keys.
I want to loop over my plainText string, insert the proper words into the string at certain offsets and then return that string.
Here is my code below
const plainText = "Hey name your food is ready, , your food has your name on it"
expected output below
mergeValues = [
{message: "Hey Keith your salmon is ready, your food has your name on it"},
{message: "Hey Kelly your pizza is ready, your food has your name on it"},
{message: "Hey Ed your hamburger is ready, your food has your name on it"},
{message: "Hey Shelby your sushi is ready, your food has your name on it"}
]
const people = [
{ name: "keith", food: "salmon"},
{ name: "kelly", food: "pizza"},
{ name: "ed", food: "hamburger"},
{ name: "shelby", food: "sushi"}
]
const locations = [
{offset: 4, length: 4, field: 'name'},
{offset: 13, length: 4, field: 'food'}
]
Here I am mapping over people, creating an object, then running a forEach on locations, and finally returning that object back to the map to let it run again on the next person in people array. Im pretty sure my main issue is that I am Rewriting over the object everytime in the forEach loop instead of modifying the string, saving that value, then modifying that string again, saving value etc.....
const mergeValues = people.map((person) => {
const messageObj = {message: ""};
locations.forEach((location) => {
if(Object.keys(person).includes(location.field)) {
messageObj.message = plainText.substring(0, location.offset + 1) + person[location.field] + plainText.substring(location.length + location.offset + 1, plainText.length)
}
})
return messageObj
messageObj.messagein your forEach, but overwriting it from the originalplainTextso it will only ever reflect the last match found. You should be initializingmessagewithplainTextand then mutating it, but keep in mind that the offsets won't match after the first mutation