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 check if there is some value inside array of objects (which is also an object) in javascript?

I have this object in js:

var list = {
  "1": {
    "id": "1",
    "start_date": "2019-01-14",
    "end_date": "2019-01-14",
    "text": "some text one",
    "assistent": "12"
  },
  "2": {
    "id": "2",
    "start_date": "2021-12-01",
    "end_date": "2021-12-01",
    "text": "another text",
    "assistent": "15"
  },
  "3": {
    "id": "3",
    "start_date": "2021-12-02",
    "end_date": "2021-12-02",
    "text": "one more text",
    "assistent": "2"
  } 
}

I want to check, if there is an "assistent"=2 inside this array of objects, and, if yes, get a "text" parameter for this assistent (it have to be "one more text"). What i have tried:

var foundtext = list.find(x => x.assistent === '2').text;
console.log(foundtext);

(will show that .find is not a function)
Also:

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

var foundtext = list.find(x => x.assistent == '2')['text'];
console.log(foundtext);

(will show the same error)

Also tried this:

for (var i=1; i <= list.length; i++) {
console.log(list[i]);
//and than perform the search inside list[i];
}

and this :

list.forEach(value => {
  console.log(value);
//and than perform the search inside value;
})

So what is the right approach to perform this kind of check?

>Solution :

I would do something like this.

const text = Object.values(list).find(entry => entry.assistent === "2")?.text

EDIT

For the additional question in the comments below.

const texts = Object.values(list)
                    .filter(entry => entry.assistent === "2")
                    .map(entry => entry.text)
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