简体   繁体   English

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

[英]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 个)

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.不要使用任何 for/while 循环或 Array#forEach。
  • Do not create any unnecessary functions eg helpers.不要创建任何不必要的功能,例如助手。

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 » 寻求帮助运行: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;
    });
}

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 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.

相关问题 按 object 属性值过滤数组 - Filter array by object property values 如何通过多个属性值过滤对象数组? - How to filter an array of object by multiple property values? 循环通过 object 并返回特定属性的值 - Loop through an object and return the values of a specific property Javascript 过滤数组中的对象并返回数组中 Object 中 Object 的属性 - Javascript Filter Objects in Array and return Property of Object in Array of Object in Array 过滤对象数组以返回具有最新日期属性的对象 - Filter object array to return the object with the latest date property 按作为属性的对象的属性过滤 - Filter by property of a object that is a property 返回特定对象的属性值 RXJS.map and.filter - Return specific object's property value RXJS .map and .filter 如何在对象属性中使用角度过滤器搜索,其中属性的值在视图中用$或者像V,Amp这样的单位格式化? - How to use angular filter search on object properties where property's values are formatted with signs like $ or units like V, Amp, in the view? AngularJS + MEANJS-使用对象模型属性作为过滤器的数组键 - AngularJS + MEANJS - Use object model property as array key for filter AngularJS ngRepeat-使用复选框按单个对象属性过滤列表 - AngularJS ngRepeat - Use checkbox to filter list by single object property
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM