我有一个纯文本对象。我还有一系列对象。在该对象数组中,每个对象都包含偏移量和长度键。
我想循环遍历我的纯文本字符串,将正确的单词插入到字符串中的某些偏移处,然后返回该字符串。
下面是我的代码
const plainText = "Hey name your food is ready, , your food has your name on it"
预期产出低于
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'}
]
在这里,我在人员上进行映射,创建一个对象,然后在位置上运行 forEach,最后将该对象返回到地图以让它在人员数组中的下一个人上再次运行。
我很确定我的主要问题是我每次在 forEach 循环中重写对象,而不是修改字符串,保存该值,然后再次修改该字符串,保存值等等......
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