1

I am new to JSON data manipulation and I would like some help.

I have a JSON file that looks like the below:

[
  {
    "plannification": {
      "Data": 1,
      "DataType": "GB",
      "InclusionOption1": ".",
      "Default": false,
      "PropositionId": "GBT13456",
      "EssentialLink": "greatpdf.com/pdf.pdf",
      "Term": "1",
      "Segment": "part",
      "Id": "653284",
    }
  },
  {
    "plannification": {
      "Data": 1,
      "DataType": "FR",
      "inclusionOption1": ".",
      "default": false,
      "PropositionId": "FRT13456",
      "EssentialLink": "greatpdf.com/pdf2.pdf",
      "term": "1",
      "Segment": "pro",
      "Id": "984532",
    }
  }
]

I'd like to to convert this file to object and only pull data from "Segment": “pro”, as below:

    {
      984532:{
      Segment: "pro",
      EssentialLink: "greatpdf.com/pdf.pdf",
      PropositionId: "FRT13456",
     },
      etc.. {},
}

Where do I start?

Tyfab
  • 11
  • 2

3 Answers3

1

You can filter your array using array#filter on the Segment where the value is pro. You can use array#reduce and iterate through the array and using Object#values() take out the values of each object and create your new object.

const data = [{ "plannification": { "Data": 1, "DataType": "GB", "InclusionOption1": ".", "Default": false, "PropositionId": "GBT13456", "EssentialLink": "greatpdf.com/pdf.pdf", "Term": "1", "Segment": "part", "Id": "653284" } }, { "plannification": { "Data": 1, "DataType":"FR", "inclusionOption1": ".", "default": false, "PropositionId": "FRT13456", "EssentialLink": "greatpdf.com/pdf2.pdf", "term": "1", "Segment": "pro", "Id": "984532", } } ],
      result = data.filter(o => {
        let { Segment } = Object.values(o)[0];
        return Segment === 'pro';
      }).reduce((r,o) => {
        let { Id, Segment, PropositionId, EssentialLink } = Object.values(o)[0];
        r[Id] = { Segment, PropositionId, EssentialLink };
        return r;
      },{})
console.log(result);
Hassan Imam
  • 21,956
  • 5
  • 41
  • 51
0

1 - Read the json file

2 - Iterate over the array of objects

3 - For every object, check your desired property

4 - If it matchs what you want, read the properties of the object and construct your object

jonhid
  • 2,075
  • 1
  • 11
  • 18
0

your data structure is not valid, at first correct the way you've written your json array of object so that i can figure out