[英]use filter to return property values in an object
Trying to make a function that uses filter but not a for or while loop or foreach function, that will loop through an array of objects only to return their property values.尝试创建一个使用 filter 而不是 for 或 while 循环或 foreach 函数的函数,该函数将遍历对象数组仅返回其属性值。 For example,例如,
function getShortMessages(messages) {
return messages.filter(function(obj){
return obj.message
});
}
so if I call所以如果我打电话
getShortMessages([{message:"bleh"},{message:"blah"}]);
I should get a return of an array = ["bleh","blah"] I'm just not sure how to implement filter under these guidelines.我应该得到一个数组的返回值 = ["bleh","blah"] 我只是不确定如何在这些准则下实现过滤器。 Also I was thinking of using a chain function maybe .map.我也在考虑使用链函数,也许是 .map。
//// Here is the entire code challenge specification///// //// 这里是整个代码挑战规范////
Basic: Filter Exercise 4 of 18基础:过滤练习 4(共 18 个)
Use Array#filter to write a function called getShortMessages.使用 Array#filter 编写一个名为 getShortMessages 的函数。
getShortMessages takes an array of objects with '.message' properties and returns an array of messages that are less than < 50 characters long. getShortMessages 接受具有“.message”属性的对象数组,并返回长度小于 50 个字符的消息数组。
The function should return an array containing the messages themselves, without their containing object.该函数应该返回一个包含消息本身的数组,而不是包含它们的对象。
{
message: 'Esse id amet quis eu esse aute officia ipsum.' // random
}
[ 'Tempor quis esse consequat sunt ea eiusmod.',
'Id culpa ad proident ad nulla laborum incididunt.',
'Ullamco in ea et ad anim anim ullamco est.',
'Est ut irure irure nisi.' ]
function getShortMessages(messages) {
// SOLUTION GOES HERE
}
module.exports = getShortMessages
» To print these instructions again, run: functional-javascript print » To execute your program in a test environment, run: functional-javascript run program.js » To verify your program, run: functional-javascript verify program.js » For help run: functional-javascript help » 要再次打印这些指令,请运行:functional-javascript print » 要在测试环境中执行您的程序,请运行:functional-javascript run program.js » 要验证您的程序,请运行:functional-javascript verify program.js » 寻求帮助运行:function-javascript help
Use .filter
when you want to get the whole object(s) that match the expected property or properties.当您想要获取与预期属性匹配的整个对象时,请使用.filter
。 Use .map
when you have an array of things and want to do some operation on those things and get the result.当你有一个数组并且想要对这些东西做一些操作并得到结果时,请使用.map
。
The challenge is to get all of the messages that are 50 characters or less.挑战在于获取 50 个字符或更少的所有消息。 So you can use filter
to get only the messages that pass that test and then map
to get only the message text.因此,您可以使用filter
仅获取通过该测试的消息,然后map
以仅获取消息文本。
function getShortMessages(messages) {
return messages
.filter(function(obj) {
return obj.message.length <= 50;
})
.map(function(obj) {
return obj.message;
});
}
JSFiddle: http://jsfiddle.net/rbbk65sq/ 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:如果输入对象可能没有message
属性,您可能需要使用obj.message && obj.message.length <= 50
来测试它,如下所示:
function getShortMessages(messages) {
return messages
.filter(function(obj) {
return obj.message && obj.message.length <= 50;
})
.map(function(obj) {
return obj.message;
});
}
The same code samples in ES6: 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:如果输入对象可能没有message
属性:
const getShortMessages = (messages) => messages
.filter(obj => obj.message && obj.message.length <= 50)
.map(obj => obj.message);
JSFiddle: http://jsfiddle.net/npfsrwjq/ JSFiddle: http : //jsfiddle.net/npfsrwjq/
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:我会像上面那样使用 es6 语法,如下所示:
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);
With custom return value (Simple ES6 Example);带有自定义返回值(简单的 ES6 示例);
const customReturnFiltere = (result) => {
return products.filter((obj) => {
return obj.stock !== 0;
})
.map((finalResult) => {
return {
...finalResult,
info: 'product will be filtered if stock is 0'
}
});
}
In addition, I am using ES6 Destructure with filter and compare two object array.此外,我使用带有过滤器的 ES6 解构并比较两个对象数组。 And finally map specific fields those i need actually.最后映射我实际需要的特定字段。
Initialization初始化
const bumperDealRules =[]; // Array object
const cartItems =[]; // Array object
Final code最终代码
const bumperDealsSelected = bumperDealRules.filter(
({ item_display_id: item_display_id, purchasequantity: purchasequantity })
=> cartItems.some(({ id: id, action_from: action_from, order_qty: order_qty })
=> id === item_display_id && purchasequantity <= order_qty && action_from == 'bumper_deal' )
).map(function(obj) {
return {
bumper_deal_company_name_id: obj.bumper_deal_company_name_id,
from_amount: obj.from_amount,
to_amount: obj.to_amount,
discount: obj.discount,
highest_limit: obj.highest_limit
};
});
In case someone is looking for a single pass through it can be done with .reduce()
如果有人正在寻找单次通过,可以使用.reduce()
So instead of doing:所以,而不是做:
const getShortMessages = (messages) => messages
.filter(obj => obj.message.length <= 50)
.map(obj => obj.message);
You can do:你可以做:
const getShortMessages = (messages) => {
return messages.reduce((shortMessages, i) => {
if (i.message.length <= 50) {
shortMessages.push(i.message)
}
return shortMessages
},[])
}
Or if you want even shorter hand:或者如果你想要更短的手:
const getShortMessages = (messages) => messages.reduce((shortMessages, item) => (item.message.length <= 50)
? shortMessages=[...shortMessages,item.message] : shortMessages,[])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.