【问题标题】:Angular/Typescript Losing Keys when converting object to array将对象转换为数组时 Angular/Typescript 丢失键
【发布时间】:2021-10-05 11:04:44
【问题描述】:

我的代码返回一个转换为数组的对象,但在此过程中键被转换为 0、1、2、3 等...

原始对象具有我希望保留的 url、id、name 等描述性键。

我在这里做错了什么?我怎样才能返回一个看起来像这样的数组?:

[
  "description": "blah blah blah"
  "telephone": "101",
  "id": "bedfordshire",
  "name": "Bedfordshire Police"
]

.ts 代码:

  fetchForceDetail(){
    return this.http
    .get<ForceDetail[]>('https://data.police.uk/api/forces/' + bedfordshire)
    .pipe(map(responseData => {
      const detailArray = [];
      for (const key in responseData) {
      if (responseData.hasOwnProperty(key))
        detailArray.push(responseData[key])
      }
      return detailArray;
    }))
    .subscribe(forcedetails => {
      console.log(forcedetails);
  });
}

【问题讨论】:

  • 您的数组需要有对象或原语,而不是键值对。
  • 正如 Stavm 所说,您的预期响应无效。看起来您希望将原始对象作为一个不起作用的数组。我最好的猜测是类似于具有键和值属性的对象数组......但目前这是猜测工作。

标签: arrays angular typescript object key-value


【解决方案1】:

您可以使用 Object.keys 和 Object.values 方法将对象转换为数组

let obj = {
  description: "blah blah blah"
  telephone: "101",
  id: "bedfordshire",
  name: "Bedfordshire Police"
}

let keys = Object.keys(obj); // ['description, 'telephone', 'id', 'name']

let values = Object.values(obj); //['blah blah blah', '101', 'bedfordshire', 'Bedfordshire Police']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-09-27
    • 2019-11-07
    • 1970-01-01
    • 2019-05-17
    • 2021-06-20
    • 1970-01-01
    • 1970-01-01
    • 2021-09-03
    相关资源
    最近更新 更多