0

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:

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?

evolutionxbox
  • 3,932
  • 6
  • 34
  • 51
Antony Slahin
  • 31
  • 1
  • 5
  • `list` is not an array `[]` so `find` and `forEach` will not be defined methods you can call. Try using an array instead? – evolutionxbox Feb 01 '22 at 08:30
  • You have done very good attempts. Please know that the variable `list` is an Object. We are able to iterate over an object using `for ... of` loop - or by using `Object.keys()`, `Object.values()`, `Object.entries()`. In your case, you may want to try `Object.values(list).filter(x => x.assistent === '2')[0].text` - to get the desired `text`. – jsN00b Feb 01 '22 at 08:31
  • 1
    Thank you guys, Object.values() is what i need. – Antony Slahin Feb 01 '22 at 08:42

1 Answers1

0

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)
Oskar Hane
  • 1,824
  • 13
  • 8