return object property using lodash from array

前端 未结 4 1262
逝去的感伤
逝去的感伤 2021-01-31 19:16

I have been trying to return a property of an object by filtering it first. Here\'s what I did:

var characters = [
  { \'name\': \'barney\',  \'age\': 36, \'bloc         


        
4条回答
  •  天涯浪人
    2021-01-31 19:28

    You could use the Lodash chaining ability. As its name implies, it enables you to chain Lodash methods calls. _.filter and _.map are appropriate here:

    const characters = [
      { 'name': 'barney',  'age': 36, 'blocked': false },
      { 'name': 'fred',    'age': 40, 'blocked': true  },
      { 'name': 'pebbles', 'age': 1,  'blocked': false },
    ]
    
    const names = _(characters)
      .filter(c => c.age < 40)
      .map('name')
      .value()
    
    alert(names)


    For the record, this is how you can do in pure JS:

    const characters = [
      { 'name': 'barney',  'age': 36, 'blocked': false },
      { 'name': 'fred',    'age': 40, 'blocked': true  },
      { 'name': 'pebbles', 'age': 1,  'blocked': false },
    ]
    
    const names = characters
      .filter(c => c.age < 40)
      .map(c => c.name)
    
    alert(names)

提交回复
热议问题