Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Copy object which has a specific value

I have a scenario where i need to copy the offers (without price) if the price is greater than 0 from the following json:

const data = [
    {
        "id": "offer1",
        "Identifier": {
            "info": "some info for offer1",
            "value": "some string for offer1"
        },
        "Price": {
            "Total": 94.30
        }
    },  
    {
        "id": "offer2",
        "Identifier": {
            "info": "some info for offer2",
            "value": "some string for offer2"
        },
        "Price": {
            "Total": 0.0
        }
    },
    {
        "id": "offer3",
        "Identifier": {
            "info": "some info for offer3",
            "value": "some string for offer3"
        },
        "Price": {
            "Total": 48.50
        }
    }
];

I need to get all the offers where the price is > 0 and put them into another array with a specific format, the expected result should look like this:

const result = [
  {
    "id":"offer1",
    "reference":"offer1",
    "Identifier":{
      "info":"some info for offer1",
      "value":"some string for offer1"
    }
  },
  {
    "id":"offer3",
    "reference":"offer3",
    "Identifier":{
      "info":"some info for offer3",
      "value":"some string for offer3"
    }
  }
]

The first step I made was to filter the initial data array to exclude offers with a Total = 0.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const filteredOffers = data.filter(offer => offer.Price.Total > 0);

What should I do next to get the expected result?
Thanks.

>Solution :

You could map new objects.

const
    data = [{ id: "offer1", Identifier: { info: "some info for offer1", value: "some string for offer1" }, Price: { Total: 94.3 } }, { id: "offer2", Identifier: { info: "some info for offer2", value: "some string for offer2" }, Price: { Total: 0 } }, { id: "offer3", Identifier: { info: "some info for offer3", value: "some string for offer3" }, Price: { Total: 48.5 } }],
    result = data
        .filter(({ Price: { Total } }) => Total > 0)
        .map(({ Price, ...o }) => ({ ...o, reference: o.id }));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading