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
To get the name as comma separated string, you just need to write as
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,AayushSuppose, 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,AnandIf 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,AayushHappy Coding 😊!
0 comments:
Post a Comment