[英]retrieve unique values from the json
I know this should very easy, but I simply cannot get this thing to work. 我知道这应该很容易,但我根本无法让这件事工作。 I have an object which has the following structure:
我有一个具有以下结构的对象:
"name": "Machine 1",
"categories": [
{
"name": "Planned",
"days": [
{
"id": 0,
"date": "2015-09-14T00:00:00",
"time": 768
},
{
"id": 0,
"date": "2015-09-15T00:00:00",
"time": 1100
},
{
"id": 0,
"date": "2015-09-16T00:00:00",
"time": 356
}
]
},
{
"name": "Item 1",
"days": [
{
"id": 0,
"date": "2015-09-14T00:00:00",
"time": 1323
},
{
"id": 0,
"date": "2015-09-15T00:00:00",
"time": 1475
},
{
"id": 0,
"date": "2015-09-16T00:00:00",
"time": 668
}
]
},
So if I want to show it in a tree like structure, the returned object would look like this 因此,如果我想在结构树中显示它,返回的对象将如下所示
What I am trying to do instead of my current approach (manual iteration) 我想做什么而不是我目前的方法(手动迭代)
angular.forEach(machine.categories, function (category, index) {
angular.forEach(category.days, function (day, index) {
newData.labels.push(day.date);
});
});
is to use a already existing library (based on my research, underscore.js
should be a perfect fit for this) and to do it properly (I am trying to learn, how to work with it). 是使用一个已经存在的库(基于我的研究,
underscore.js
应该是一个完美的适合这个)并正确地做(我正在努力学习,如何使用它)。
So what I am trying to achieve is to get list of unique days in the date format. 所以我想要实现的是获取日期格式的唯一日期列表。 So my resulting object would look like this:
所以我生成的对象看起来像这样:
var result = ["2015-09-14", "2015-09-15", "2015-09-16"]
(this one would be better) var result = ["2015-09-14", "2015-09-15", "2015-09-16"]
(这个会更好)
Is there a way how to do it using the library (meaning without manual iteration)? 有没有办法如何使用库(意味着没有手动迭代)?
You could use Set
for unique values 您可以将
Set
用于唯一值
var data = { "name": "Machine 1", "categories": [{ "name": "Planned", "days": [{ "id": 0, "date": "2015-09-14T00:00:00", "time": 768 }, { "id": 0, "date": "2015-09-15T00:00:00", "time": 1100 }, { "id": 0, "date": "2015-09-16T00:00:00", "time": 356 }] }, { "name": "Item 1", "days": [{ "id": 0, "date": "2015-09-14T00:00:00", "time": 1323 }, { "id": 0, "date": "2015-09-15T00:00:00", "time": 1475 }, { "id": 0, "date": "2015-09-16T00:00:00", "time": 668 }] }] }; var set = new Set(); data.categories.forEach(e => e.days.forEach(e => set.add(e.date))); document.write('<pre>' + JSON.stringify(Array.from(set)) + '</pre>');
Using underscore (bit verbose, assuming you parsed your JSON in a variable called data
): 使用下划线(比特详细,假设您在一个名为
data
的变量中解析了JSON):
var result = _.uniq(
_.flatten(
_.map(data.categories, function(category) {
return _.map(_.pluck(category.days, 'date'), function(date) {
return date.replace(/T\d+:\d+:\d+$/, '');
});
})));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.