使用Underscore从数组中返回一个新数组

时间:2017-09-27 18:51:38

标签: javascript underscore.js

我想返回一个只包含指定值的过滤数组

var messages: [{
     id: 1,
     name: "John",
     hashtag: ["#cool"]},

     {id: 2,
     name: "Bob",
     hashtag: ["#cool", "#sweet"]},

     {id: 3,
     name: "Bob",
     hashtag: ["#sweet"]} ];

// supposed to return the first two items in the array
var newArray = _.where(messages, {hashtag: "#cool"});

3 个答案:

答案 0 :(得分:1)

你可以很好地使用Filter,但你的对象有一些语法错误。值必须是字符串。显示这个例子:



var messages=[ {
     id: 1,
     name: "John",
     hashtag: ["#cool"] },

     {id: 2,
     name: "Bob",
     hashtag: ["#cool"," #sweet"] },

     {id: 3,
     name: "Bob",
     hashtag: ["#sweet"]
	 }];
	var newArray=messages.filter(function(task){ return task.hashtag.includes("#cool") });

	console.log(newArray);




答案 1 :(得分:1)

这是一种纯粹的功能性方法,你可以使用下划线,但是,更喜欢Ramda这样的事情:



var messages = [{
    id: 1,
    name: "John",
    hashtag: ["#cool"]
  },

  {
    id: 2,
    name: "Bob",
    hashtag: ["#cool", "#sweet"]
  },

  {
    id: 3,
    name: "Bob",
    hashtag: ["#sweet"]
  }
]

var newArray = _.filter(messages, _.compose(_.partial(_.contains, _, '#cool'), _.property('hashtag')))

console.log(newArray)

<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
&#13;
&#13;
&#13;

答案 2 :(得分:1)

您无法使用_.where过滤存储在“hashtag”中的数组(因为它会在键值对中搜索字符串),但您可以使用_.filter

来执行此操作
var filtered = _.filter( messages, function( message ){
    return message['hashtag'].indexOf('#cool') !== -1;
} );

用于证明其有效的小代码:https://codepen.io/iwantwin/pen/oGWNzv