Pravu
Pravu

Reputation: 608

get specific object in array

I got problem to get specific object in array.

Example array

enter image description here

I just want id

Code

for (let item of this.commonService.popularList$.getValue()) {
        console.log(item['menuList'])
}

if I add code like this console.log(item['menuList'][id]) it display like this undefined

Upvotes: 0

Views: 302

Answers (5)

Ztemps
Ztemps

Reputation: 196

For retrieve the id that you want, just do the following:

const arr = [{ id: 9 }, { id: 15 }, { id: 18 }, { id: 25 }];
const specificId = 18;
const yourId = arr.find(({id}) => id === specificId);

console.log(yourId)

stackblitz of how it works.

Upvotes: 2

Aluan Haddad
Aluan Haddad

Reputation: 31873

It appears that this.commonService.popularList$ is an RxJS BehaviorSubject, using its GetValue()/value members may not be desirable because we will not receive any new values that are published by the BehaviorSubject.

Therefore, I will suggest an alternative to what has been suggested so far.

this.commonService.popularList$.subscribe(popularList => {
  for (const item of popularList) {
    console.log(item.id);
  }
});

This means we will always print the latest values as they come in.

Upvotes: 2

Rajdeep D
Rajdeep D

Reputation: 3920

let idArray = [];
for (let item of this.commonService.popularList$.getValue()) {
     if(item && item['menuList'] && Array.isArray(item['menuList']))
       item['menuList'].forEach(menu => idArray.push(menu.id));
}
 console.log(idArray)

Test code

let data = [{menuList:[{id:1},{id:2}]},{menuList:[{id:3},{id:4}]}];
let idArray = [];
for (let item of data) {
    if(item && item['menuList'] && Array.isArray(item['menuList']))
       item['menuList'].forEach(menu => idArray.push(menu.id));
}
console.log(idArray)

Upvotes: 2

Anil
Anil

Reputation: 121

If item['menuList'] is an array of objects then you need to put in the index as well

for (let item of this.commonService.popularList$.getValue()) {
    console.log(item['menuList'])
    for(let i=0; i<item['menuList'].length; i++){
         console.log(item['menuList'][i]['id']);//will print the ids
    }
}

Upvotes: 2

Andrew Glazier
Andrew Glazier

Reputation: 159

It appears you're accessing an array of objects.

Given the following:

const arr = [{ id: 12 }, { id: 57 }];

You can access the objects by index and then retrieve the array, the following example will provide you the id of the first item in the list (adjust 0 to whichever index you desire.)

arr[0].id

Or you could map the array to an array of simply ids like such...

arr.map(({ id }) => id)

Which would return a new array, in this example, this would equal:

[12, 57]

Upvotes: 3

Related Questions