use filter to return property values in an object
Solution 1:
Use .filter
when you want to get the whole object(s) that match the expected property or properties. Use .map
when you have an array of things and want to do some operation on those things and get the result.
The challenge is to get all of the messages that are 50 characters or less. So you can use filter
to get only the messages that pass that test and then map
to get only the message text.
function getShortMessages(messages) {
return messages
.filter(function(obj) {
return obj.message.length <= 50;
})
.map(function(obj) {
return obj.message;
});
}
JSFiddle: http://jsfiddle.net/rbbk65sq/
If it is possible for the input objects to not have a message
property, you would want to test for it with obj.message && obj.message.length <= 50
like this:
function getShortMessages(messages) {
return messages
.filter(function(obj) {
return obj.message && obj.message.length <= 50;
})
.map(function(obj) {
return obj.message;
});
}
ES6
The same code samples in ES6:
const getShortMessages = (messages) => messages
.filter(obj => obj.message.length <= 50)
.map(obj => obj.message);
And if the input objects might not have the message
property:
const getShortMessages = (messages) => messages
.filter(obj => obj.message && obj.message.length <= 50)
.map(obj => obj.message);
JSFiddle: http://jsfiddle.net/npfsrwjq/
Solution 2:
Though I realize this thread is super old, I felt it necessary to comment in the event that someone stumbles on it again. I would do it like above just using es6 syntax like this:
objects.filter(obj => obj.key === 'value').map(filteredObj => filteredObj.key);
So the above example would be:
getShortMessages = (messages) => messages.filter(obj => obj.message.length <= 50).map(obj => obj.message);