【发布时间】:2022-01-07 12:05:48
【问题描述】:
我无法访问对象(数组)中的键/值/条目,稍微更改该对象并将其推送到新的空对象(newArray)。我可以访问键、值和条目,但不能更改它们。
下面的代码可以正常工作,但我想让它不那么具体,更通用,这样我也可以在其他地方使用这个函数。
我尝试过使用 Object.keys()、Object.values() 和 Object.entries() 以及 keyof typeof x 但无济于事,因为 .replace() 对对象不起作用。
该对象以 CSV 格式下载,我使用双引号分隔字段,因为字段可能包含逗号,如果保留,则会关闭 CSV 字段。
let array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
let newArray = [];
array.forEach(s => {
let x = JSON.parse(JSON.stringify(s));
x.addressLine1 = x.addressLine1.replace(x.addressLine1, `"${x.addressLine1}"`);
x.addressLine2 = x.addressLine2 ? x.addressLine2.replace(x.addressLine2, `"${x.addressLine2}"`) : '';
x.town = x.town.replace(x.town, `"${x.town}"`);
x.postcode = x.postcode.replace(x.postcode, `"${x.postcode}"`);
newArray.push(x);
});
尝试使用 keyof typeof:
array.forEach(s => {
let x = JSON.parse(JSON.stringify(s));
let property: keyof typeof x;
for (property in x) {
property = property ? property.replace(property, `"${property}"`) : '';
newArray.push(x);
对象应如下所示:
{
"addressLine1": "\"The Road\"",
"addressLine2": "",
"town": "\"London\"",
"postcode": "\"SE1 5QH\"",
}
【问题讨论】:
-
您的对象看起来如何?您希望新的外观如何?
-
输入是什么,预期的输出是什么?尽管它们已经是字符串,但为什么要用引号将每个值括起来?
Object,keys()、.values()或.entries()的尝试在哪里? -
为什么用
angular和typescript标记?您的示例中没有任何内容与这些标签相关。 -
这段代码应该做什么?所有这些在
""中的解析和序列化、来回和包装字符串。这看起来很邪恶。 -
我添加了一个示例对象。它将以 CSV 格式下载,我使用双引号分隔字段,因为字段可能包含逗号,这会使字段关闭。我已经删除了 Angular 标签。
标签: javascript typescript object