use filter to return property values in an object

前端 未结 5 1733
礼貌的吻别
礼貌的吻别 2020-12-24 00:55

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.

相关标签:
5条回答
  • 2020-12-24 01:19

    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);
    
    0 讨论(0)
  • 2020-12-24 01:24

    In addition, I am using ES6 Destructure with filter and compare two object array. 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
                 };
              });
    
    0 讨论(0)
  • 2020-12-24 01:26

    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/

    0 讨论(0)
  • 2020-12-24 01:32

    With custom return value (Simple ES6 Example);

    const customReturnFiltere = (result) => {
        return products.filter((obj) => {
          return obj.stock !== 0;
        })
        .map((finalResult) => {
            return {
              ...finalResult,
              info: 'product has been filtered if stock is 0'
            }
        });
    }
    
    0 讨论(0)
  • 2020-12-24 01:33

    In case someone is looking for a single pass through it can be done with .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,[])
    
    0 讨论(0)
提交回复
热议问题