[英]Extract 1 of each property from object
I am looking for a method using lodash/underscore(or plain JS if one does not exist) that will only me to take a given object such as below. 我正在寻找一种使用lodash / underscore的方法(或者如果不存在,则使用纯JS),这种方法只会让我采用如下所示的给定对象。
animals: {
{
type: 'duck',
name: 'quack',
},
{
type: 'duck',
name: 'quieck',
},
{
type: 'dog',
name: 'bark',
},
},
This object for example contains 3 different animals, but two of them are the same type. 例如,此对象包含3种不同的动物,但其中两种是同一类型。
The end result is to be able to use a control structure such as a for loop to iterate through each TYPE of animal, such that I'm working with something that only has one instance of each type. 最终结果是能够使用诸如for循环之类的控制结构来遍历每种类型的动物,从而使我使用的每种类型只有一个实例的东西。
This is being used because I am creating a list. 因为我正在创建列表,所以正在使用它。
This list will be similar to the following 此列表将类似于以下内容
duck
name is quack
name is quick
dog
name is bark
But i want to do this with control structures and not by simply outputting and hardcoding in each name, as this list will get very extensive and long. 但是我想使用控制结构来实现此目的,而不是简单地在每个名称中进行输出和硬编码,因为此列表将变得非常广泛和冗长。
I would use the uniq function. 我会使用uniq函数。
var uniqueAnimals = _.uniq(animals, function(item, key, type) {
return item.type;
});
Presuming animals
is not a syntax error, but an array: If you don't just want to filter the unique types but also create a structure for your output, you could go with an object: 假定
animals
不是语法错误,而是数组:如果您不仅要过滤唯一类型,而且还想为输出创建结构,则可以使用一个对象:
var kv = {};
animals.forEach(function(a) {
if(kv[a.type]) {
kv[a.type].push(a.name);
} else {
kv[a.type] = [];
}
}
Later, you could iterate Object.keys(kv)
to print your key/values 稍后,您可以迭代
Object.keys(kv)
以打印键/值
_.groupBy() maybe? _.groupBy() ?
var animals = [ { type: 'duck', name: 'quack', }, { type: 'duck', name: 'quieck', }, { type: 'dog', name: 'bark', }, ]; var grouped = _.groupBy(animals, 'type'); document.write('<pre>' + JSON.stringify(grouped, null, 3) + '</pre>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.6.1/lodash.min.js"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.