在 javascript 代码中简化类似的对象文字
Simplify similar Object Literal in javascript code
有什么方法可以简化这段代码,我很感激任何想法。
在 lyerDefs 中,我对从 1 到 11 的所有对象具有相同的值。
spider = L.esri.dynamicMapLayer({
url:API,
layers:[1,2,3,4,5,6,7,8,9,10,11],
layerDefs:{ // how to simplify following code?
1: "Site_id ='"+ activeSiteId +"'",
2: "Site_id ='" + activeSiteId +"'",
3: "Site_id ='"+ activeSiteId +"'",
4: "Site_id ='"+ activeSiteId +"'",
5: "Site_id ='"+ activeSiteId +"'",
6: "Site_id ='"+ activeSiteId +"'",
7: "Site_id ='"+ activeSiteId +"'",
8: "Site_id ='"+ activeSiteId +"'",
9: "Site_id ='"+ activeSiteId +"'",
10: "Site_id ='"+ activeSiteId +"'",
11: "Site_id ='"+ activeSiteId +"'"
}
} );
这取决于你简化它的意思。我假设您不想重复 "Site_id = '" + activeSiteId +"'" 字符串 11 次。如果仅此而已,那么应该这样做:
var layers = [];
var layerDefs = {};
for(i = 1; i < 12; i++) {
layers.push(i);
layerDefs[i] = "Site_id = '" + activeSiteId + "'";
}
spider = L.esri.dynamicMapLayer({
url:API,
layers: layers,
layerDefs: layerDefs
});
您可以创建一个函数来生成图层和 layerDef。下面的示例使用 .reduce
方法。
function generateLayersAndDefs(layers) {
return {
layers: layers,
layerDefs: layers.reduce(function(final, current) {
final[current] = "Site_id ='" + current + "'"
return final;
}, {})
};
}
spider = L.esri.dynamicMapLayer(
Object.assign(
{
url:API
},
generateLayersAndDefs([1,2,3,4,5,6,7,8,9,10,11])
)
);
有什么方法可以简化这段代码,我很感激任何想法。 在 lyerDefs 中,我对从 1 到 11 的所有对象具有相同的值。
spider = L.esri.dynamicMapLayer({
url:API,
layers:[1,2,3,4,5,6,7,8,9,10,11],
layerDefs:{ // how to simplify following code?
1: "Site_id ='"+ activeSiteId +"'",
2: "Site_id ='" + activeSiteId +"'",
3: "Site_id ='"+ activeSiteId +"'",
4: "Site_id ='"+ activeSiteId +"'",
5: "Site_id ='"+ activeSiteId +"'",
6: "Site_id ='"+ activeSiteId +"'",
7: "Site_id ='"+ activeSiteId +"'",
8: "Site_id ='"+ activeSiteId +"'",
9: "Site_id ='"+ activeSiteId +"'",
10: "Site_id ='"+ activeSiteId +"'",
11: "Site_id ='"+ activeSiteId +"'"
}
} );
这取决于你简化它的意思。我假设您不想重复 "Site_id = '" + activeSiteId +"'" 字符串 11 次。如果仅此而已,那么应该这样做:
var layers = [];
var layerDefs = {};
for(i = 1; i < 12; i++) {
layers.push(i);
layerDefs[i] = "Site_id = '" + activeSiteId + "'";
}
spider = L.esri.dynamicMapLayer({
url:API,
layers: layers,
layerDefs: layerDefs
});
您可以创建一个函数来生成图层和 layerDef。下面的示例使用 .reduce
方法。
function generateLayersAndDefs(layers) {
return {
layers: layers,
layerDefs: layers.reduce(function(final, current) {
final[current] = "Site_id ='" + current + "'"
return final;
}, {})
};
}
spider = L.esri.dynamicMapLayer(
Object.assign(
{
url:API
},
generateLayersAndDefs([1,2,3,4,5,6,7,8,9,10,11])
)
);