-1

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?

My code:

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

const Single = ({ inputs, title }) => {
  const { state } = useLocation();
  let data1 = state.foo;
  console.log(data1);
Ava
  • 512
  • 2
  • 26
  • 3
    Use `Array.prototype.find` function: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find – Ram Sep 13 '22 at 11:27
  • You can use [filter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) like `data1.filter(el => el.id === 35)` or `data1.filter(el => el.id === 35)[0]` – Simone Rossaini Sep 13 '22 at 11:29
  • @SimoneRossaini this kind of code is outdated by about half a decade. – Thomas Sep 13 '22 at 11:40
  • @Thomas But who says that? You? Does the code work? Has the `filter` method been deprecated? – Simone Rossaini Sep 13 '22 at 11:57
  • i tried with `filter` and it didn't work for me – Ava Sep 13 '22 at 12:00
  • @SimoneRossaini why do you use `.filter()` and not a `.forEach()` with an `array.push()`? 'Are `.forEach` or `array.push()` deprecated? `filter` is not bad per se, but using `.filter(...)[0]` instead of `.find(...)` is outdated coding style. First, `filter` continues to iterate over the entire array, even after it has a match and second, it returns an unnecessary array from which you then have to get your value. Neither comes for free. `find` returns as soon as it found a matching element and it returns you the element itself and not wrapped in an array that you neither need nor want. – Thomas Sep 13 '22 at 12:28

1 Answers1

1

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
polmina
  • 26
  • 3