我有两个geoJSON文件,我想为D3可视化嵌套。这个问题同样适用于javascript中的两个关联数组/对象。这是最简洁的方式吗?如何从用于第二个数组的变量名生成密钥名称[“communities”]?这使用下划线/ lodash函数_.where()。因为我使用d3是有一种方法来做到这一点没有lo-dash依赖(不是必要的,但如果有一个内置的d3函数来做到这一点,更好)。
var nationalities = [{
"type": "Feature",
"properties": {
"nationality": "Cofan"
},
"geometry": null
}, {
"type": "Feature",
"properties": {
"nationality": "Secoya"
},
"geometry": null
}
];
var communities = [{
"type": "Feature",
"properties": {
"community": "Dureno",
"nationality": "Cofan"
},
"geometry": null
}, {
"type": "Feature",
"properties": {
"community": "Zabalo",
"nationality": "Cofan"
},
"geometry": null
}, {
"type": "Feature",
"properties": {
"community": "Duvono",
"nationality": "Cofan"
},
"geometry": null
}
];
var nested = nest(nationalities, communities, "nationality");
console.log(nested);
function nest(array1, array2, id) {
var filterFunc = function(feature) {
return function(d) {
return feature.properties[id] === d.properties[id];
};
};
array1.forEach(function(feature) {
feature.properties["communities"] = _.filter(array2, filterFunc(feature));
})
return array1;
}