2

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?

3 Answers 3

1

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!

Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

Thank all of you so much - solved. All of the solutions work perfectly well!
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.