【问题标题】:Javascript - Mapping over an object, changing key/values in the object and pushing to new objectJavascript - 映射对象,更改对象中的键/值并推送到新对象
【发布时间】: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() 的尝试在哪里?
  • 为什么用angulartypescript标记?您的示例中没有任何内容与这些标签相关。
  • 这段代码应该做什么?所有这些在"" 中的解析和序列化、来回和包装字符串。这看起来很邪恶。
  • 我添加了一个示例对象。它将以 CSV 格式下载,我使用双引号分隔字段,因为字段可能包含逗号,这会使字段关闭。我已经删除了 Angular 标签。

标签: javascript typescript object


【解决方案1】:

您可以尝试不要“字符串化”您的对象并直接从对象中创建它。

也许是这样的(我在这里给你留下一个工作示例): https://codesandbox.io/s/dark-dawn-w85z3

let objArray = [
  {
    addressLine1: "anothernamefieldexampleline1",
    addressLine2: "exampleline2",
    town: "exampletown1",
    postcode: "examplepostcode1"
  },
  {
    addressLine1: "exampleline1b",
    addressLine2: "exampleline2b",
    town: "exampletown1b",
    postcode: "examplepostcodeb"
  }
];
let array = typeof objArray != "object" ? JSON.parse(objArray) : objArray;

let newArray = array.map((_itemObject) => {

  let returnObject={};


  let arrayKeyProperties = [];
  for (const key in _itemObject) {
    arrayKeyProperties.push(key);
  };

  console.log(arrayKeyProperties);

  arrayKeyProperties.forEach(
    (_prop) => returnObject[_itemObject[_prop]] = _itemObject[_prop]
  );

  return returnObject;
});

console.log(newArray);

我展示了输出的图像,其中创建的数组带有带有新字段名称的新对象(基于旧字段的值)。

【讨论】:

  • 感谢您的尝试,但是我试图避免提及特定键,因为我希望能够在其他地方使用它并使用 Object.keys(array) 作为示例,因此它会遍历所有键那个对象,我没有具体提到每一个。
  • 好吧,我没听明白。我编辑了我以前的答案来解决你的问题。尝试使用新方法(用于通用键)并发表评论。
猜你喜欢
  • 2020-06-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-11
  • 2020-06-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多