Javascript 使用过滤器返回对象中的属性值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31201262/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:22:33  来源:igfitidea点击:

use filter to return property values in an object

javascriptfilter

提问by codemonkey

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. For example,

尝试创建一个使用 filter 而不是 for 或 while 循环或 foreach 函数的函数,该函数将遍历对象数组仅返回其属性值。例如,

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. Also I was thinking of using a chain function maybe .map.

我应该得到一个数组的返回值 = ["bleh","blah"] 我只是不确定如何在这些准则下实现过滤器。我也在考虑使用链函数,也许是 .map。

//// Here is the entire code challenge specification/////

//// 这里是整个代码挑战规范////

Basic: Filter Exercise 4 of 18

基础:过滤练习 4(共 18 个)

Task

任务

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.

该函数应该返回一个包含消息本身的数组,而不是包含它们的对象。

Arguments

参数

  • messages: an Array of 10 to 100 random objects that look something like this:
  • 消息:一个由 10 到 100 个随机对象组成的数组,看起来像这样:
{
    message: 'Esse id amet quis eu esse aute officia ipsum.' // random
}

Conditions

状况

  • Do not use any for/while loops or Array#forEach.
  • Do not create any unnecessary functions e.g. helpers.
  • 不要使用任何 for/while 循环或 Array#forEach。
  • 不要创建任何不必要的功能,例如助手。

Hint

暗示

  • Try chaining some Array methods!
  • 尝试链接一些 Array 方法!

Example

例子

[ '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.' ]

Resources

资源

Boilerplate

样板

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 ? 如需帮助,请运行:functional-javascript help

回答by Cymen

Use .filterwhen you want to get the whole object(s) that match the expected property or properties. Use .mapwhen you have an array of things and want to do some operation on those things and get the result.

.filter当您想要获取与预期属性匹配的整个对象时使用。使用.map时,你有一个事物的数组,并希望做这些事情的一些操作和得到的结果。

The challenge is to get all of the messages that are 50 characters or less. So you can use filterto get only the messages that pass that test and then mapto get only the message text.

挑战在于获取 50 个字符或更少的所有消息。因此,您可以使用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 messageproperty, you would want to test for it with obj.message && obj.message.length <= 50like 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;
    });
}

ES6

ES6

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 messageproperty:

如果输入对象可能没有该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/

回答by jbalesteri

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);

回答by Aathi

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 has been filtered if stock is 0'
        }
    });
}