简体   繁体   English

移除 JavaScript 中嵌套对象的层级

[英]Removing levels in nested objects in JavaScript

A REST API which I use returns this data format:我使用的 REST API 返回以下数据格式:

const documents = [
  {
    "fields": {
      "title": {
        "stringValue": "77"
      },
      "difficulty": {
        "doubleValue": 77
      },
    },
    "createTime": "2020-04-10T15:13:47.074204Z"
  },
  {
    "fields": {
      "title": {
        "stringValue": "99"
      },
      "difficulty": {
        "doubleValue": 99
      },
    },
    "createTime": "2020-04-10T15:13:47.074204Z"
  }
]

What I need is this format:我需要的是这种格式:

{
  title: "77",
  difficulty: 77
},
{
  title: "99",
  difficulty: 99
}

Which means I have to not only group this data but entirely remove two layers in the middle.这意味着我不仅要对这些数据进行分组,还要完全删除中间的两层。 How do I do that?我怎么做?

As a bonus: How do I get better at this?作为奖励:我如何在这方面做得更好? Are there any good resources?有什么好的资源吗?

By using .map() and destructuring as the following:通过使用.map()和解构如下:

 const documents = [{ "fields": { "title": { "stringValue": "77" }, "difficulty": { "doubleValue": 77 }, }, "createTime": "2020-04-10T15:13:47.074204Z", }, { "fields": { "title": { "stringValue": "99" }, "difficulty": { "doubleValue": 99 }, }, "createTime": "2020-04-10T15:13:47.074204Z" } ]; const result = documents.map(({fields}) => ({title: fields.title.stringValue, difficulty: fields.difficulty.doubleValue})); console.log(result);

I hope this helps!我希望这有帮助!

You can use Array#map method and Object.values method to achieve the result.您可以使用Array#map方法和Object.values方法来实现结果。

 const documents = [{ "fields": { "title": { "stringValue": "77" }, "difficulty": { "doubleValue": 77 }, }, "createTime": "2020-04-10T15:13:47.074204Z" }, { "fields": { "title": { "stringValue": "99" }, "difficulty": { "doubleValue": 99 }, }, "createTime": "2020-04-10T15:13:47.074204Z" } ] const result = documents.map(({ fields: { title: t, difficulty: d } }) => ({ title: Object.values(t)[0], difficulty: Object.values(d)[0] })); console.log(result);

You'll have to iterate through the data and pick your fields.您必须遍历数据并选择您的字段。 A descriptive way to do that is by using the map() function available on arrays.一种描述性的方法是使用 arrays 上提供的map() function。

 const documents = [ { "fields": { "title": { "stringValue": "77" }, "difficulty": { "doubleValue": 77 }, }, "createTime": "2020-04-10T15:13:47.074204Z" }, { "fields": { "title": { "stringValue": "99" }, "difficulty": { "doubleValue": 99 }, }, "createTime": "2020-04-10T15:13:47.074204Z" } ] let result = documents.map(document => ({ title: document.fields.title.stringValue, difficulty: document.fields.difficulty.doubleValue })); console.log(result);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM