[英]Filter nested array of objects by object property in d3.js
I have a meteorite landings dataset. 我有一个陨石着陆数据集。
I nested the data in four keys, by type: 我按以下类型将数据嵌套在四个键中:
var dataByType = d3.nest()
.key(function(d) {
return d.rectype;
})
.entries(dataset); // the original array
This is the resulting structure: data 这是结果结构: 数据
Now I want to create new arrays , filtering the nested one: I want each filtered array to contain only the objects whose "mass" property is inside a defined range . 现在我想创建新的数组 ,过滤嵌套的数组 :我希望每个过滤的数组只包含“mass”属性在定义范围内的对象 。
So I tried this: 所以我尝试了这个:
// filter small meteorites
var lightWeight = dataByType.forEach(function(d){
d.values.filter(function (object) {
var mass = object.mass;
return mass <= 100;
});
});
But it returns undefined . 但它返回undefined 。
Nesting is giving me a lot of trouble! 嵌套给我带来了很多麻烦! What do I do wrong? 我做错了什么?
Thanks in advance 提前致谢
I think you're overwriting lightWeight on each pass of that forEach. 我认为你在每次传递forEach时都会覆盖lightWeight。 Instead try creating lightWeight as its own object, then adding the keys you want in the loop: 而是尝试将lightWeight创建为自己的对象,然后在循环中添加所需的键:
const lightWeight = {};
dataByType.forEach(function(d){
lightWeight[d.key] = d.values.filter(function (object) {
var mass = object.mass;
return mass <= 100;
});
});
Working pen which (I think?) is doing what you want: https://codepen.io/benjaminwfox/pen/veBjrP?editors=0012 工作笔(我认为?)正在做你想做的事: https : //codepen.io/benjaminwfox/pen/veBjrP?edit = 0012
我无法说出你的数据集是什么样的,但是它可能只是你最后没有返回lightWeight
吗?
I am unsure what you are trying to filter on exactly, but try to use map
instead of forEach
and you need to return d
in the iterators, anon function. 我不确定你要过滤的是什么,但是尝试使用map
而不是forEach
,你需要在迭代器,anon函数中返回d
。
Like the following: 如下:
var lightWeight = dataByType.map(function(d) {
d.filteredValues = d.values.filter(function (object) {
return object.mass <= 100;
});
return d;
});
Assuming that you got the data
in the format you shared, where for each item of data
you have a key
property and a values
array. 假设您获得了共享格式的data
,每个data
项都有一个key
属性和一个values
数组。
If you want to filter the values
array by the mass
property of each entry, you will need to use a combination of .map()
and .filter()
methods. 如果.filter()
每个条目的mass
属性过滤values
数组,则需要使用.map()
和.filter()
方法的组合。
This is how should be your code: 这是你的代码应该如何:
var lightWeight = data.map(function(d){
var obj = {};
obj.key = d.key;
obj.values = d.values.filter(function (object) {
return object.mass <= 100;
});
return obj;
});
This will give you the expected results. 这将为您提供预期的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.