使用JavaScript浅层克隆对象的有效方法是什么?


//function for creating a shallow object and remove the multiple spaces
export const getTrimmedValues = (values) => {
const shallowValues = {
...values,
};
for (const key in shallowValues.primaryInformation) {
const currentValue = shallowValues.primaryInformation[key];
if (typeof currentValue === 'string') {
shallowValues.primaryInformation[key] = currentValue.replace(/s+/g, ' ').trim();
}
}
return shallowValues;
};

//Original Object
const values = {
otherObject: {}
otherArray: []
primaryInformation: {
email: "test.test@testdata.com"
externalId: "DSB-External test"
firstName: "Dave External test    test"
isGood: true
isHeaven: false
lastName: "Bacay External"
userId: 656555
}
}
//calling the function
getTrimmedValues(values)

我想从原始对象创建一个浅对象,并通过使用浅对象和for循环编辑字符串以删除多个空格,我认为我以错误的方式实现了它。

感谢所有的建议和评论。

这里可以利用JSON。Stringify函数有第二个参数,因为替换函数在对象的每个键上进行内部迭代。请检查以下代码

//Original Object
const values = {
otherObject: {},
otherArray: [],
primaryInformation: {
email: "dave.external@testdata.com",
externalEmployeeId: "DSB-External test   ",
firstName: "Dave External test    test",
isActive: true,
isExternal: false,
lastName: "Bacay External",
userId: 656555,
}
};
function getTrimmedValues(obj) {
let str = JSON.stringify(obj, (key, value) => {
if(typeof value === 'string') {
return value.replace(/s+/g, ' ').trim()
}
return value;
});
return JSON.parse(str);
}
console.log(getTrimmedValues(values));

最新更新