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

How to extract value of a property of array of objects?

I have this data (data1) below, an array of objects with multiple objects inside:

[
    {
        "id": 35,
        "code": "BP  S",
        "article": "BP  S",
        "price": 100,
        "vat": null,
        "status": null,
        "company_id": 12
    },
    {
        "id": 36,
        "code": "B P  S",
        "article": "BPS",
        "price": 100,
        "vat": null,
        "status": null,
        "company_id": 12
    }
]

I would like to extract the code of the first id=35.

How to do that?

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

My code:

import { useLocation } from "react-router-dom";

const Single = ({ inputs, title }) => {
  const { state } = useLocation();
  let data1 = state.foo;
  console.log(data1);

>Solution :

You could use the High order function find to retrieve the item of the array matching the id = 35 , as in:

const item = data1.find((el)=>el.id===35)

Then you could extract the code with:

item.code

Or you could chain them:

const code = data1.find((el)=>el.id===35).code
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