简体   繁体   中英

Removing levels in nested objects in JavaScript

A REST API which I use returns this data format:

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:

 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.

 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.

 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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