删除 JavaScript 中嵌套对象中的级别

Removing levels in nested objects in JavaScript

A REST API 我使用 returns 这种数据格式:

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"
  }
]

我需要的是这样的格式:

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

这意味着我不仅要对这些数据进行分组,还要完全删除中间的两层。我该怎么做?

作为奖励:我如何才能做得更好?有什么好的资源吗?

通过使用 .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);

希望对您有所帮助!

您可以使用Array#map method and 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);

您必须遍历数据并选择您的字段。一种描述性的方法是使用数组上可用的 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"
  }
]

let result = documents.map(document => ({
  title: document.fields.title.stringValue,
  difficulty: document.fields.difficulty.doubleValue
}));

console.log(result);