Angular: Get Comma separated string for one Property from an Array of Objects

This is a small useful snippet which will explain how to get a comma separated string for one property from an array of objects.

If following is your array of objects
var usersArray = [
    {
        id: "1",
        name: "Ram",
        active: true
    },
    {
        id: "2",
        name: "Jishith",
        active: false
    },
    {
        id: "3",
        name: "Anand",
        active: true
    },
    {
        id: "4",
        name: "Aayush",
        active: false
    }
];

To get the name as comma separated string, you just need to write as
var userNames = users.map(s => s.name).toString();
console.log(userNames);
The output will be
Ram,Jishith,Anand,Aayush

Suppose, if you want to get only active user list
var userNames = users.filter(s => s.active == true).map(s => s.name).toString();
console.log(userNames);
The output will be
Ram,Anand
If you want to filter with an array of values for an property, you have to use as below
var userIds=[2,3,4]
var userNames = users.filter(function (item) {
          return this.userIds.includes(item.id)
        }).map(s => s.name).toString(); 
console.log(userNames);
The output will be
Jishith,Anand,Aayush
Happy Coding 😊!

Gopikrishna

    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment