use filter to return property values in an object

前端 未结 5 1758
礼貌的吻别
礼貌的吻别 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: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,[])
    

提交回复
热议问题