![](/img/trans.png)
[英]Merge property from an array of objects into another based on property value lodash
[英]Selecting a 'property value' from an array based on another 'property value' in javascript
我有这样的数组。
var nodes = [{ID:"101", x:100, y:200}
,{ID:"102", x:200, y:200}
,{ID:"103", x:300, y:300}
,{ID:"104", x:200, y:300}];
我想要一个函数,该函数将节点的ID作为输入并返回其(x,y)。 例如,函数coordinates(103)
应该读取数组(节点)并在调用时返回x = 300,y = 300。 任何指针表示赞赏。 谢谢:)这就是我到目前为止。 它有效,但是我想知道更整洁的方法。
function coordinates(id){
for (var i=0 in nodes){
if(nodes[i].ID == id){
return { x: nodes[i].x, y: nodes[i].y};
}
}
}
console.log(coordinates(102));
查看内联评论:
var nodes = [{ ID: "101", x: 100, y: 200 }, { ID: "102", x: 200, y: 200 }, { ID: "103", x: 300, y: 300 }, { ID: "104", x: 200, y: 300 }]; var noOfCord = nodes.length; var coordinates = function(id) { for (var i = 0; i < noOfCord; i++) { if (nodes[i].ID == id) { return { x: nodes[i].x, y: nodes[i].y }; } } } document.write(coordinates(103).x + ', ' + coordinates(103).y);
您可以像这样使用.filter
var nodes = [{ ID: "101", x: 100, y: 200 }, { ID: "102", x: 200, y: 200 }, { ID: "103", x: 300, y: 300 }, { ID: "104", x: 200, y: 300 }]; function coordinates(nodes, id) { var result = nodes.filter(function (el) { return +el.ID === id; }); if (result && result.length) { result = result[0]; return { x: result.x, y: result.y }; } return null; } console.log(coordinates(nodes, 103));
基本上你在看这样的东西
var f = function(id){
var match = nodes.filter(function(d){
return d.ID === id;
})
return match && match.length && {x: match[0].x, y:match[0].y}
|| {x: undefined, y: undefined};
};
然后f('101')
输出{x: 100, y:200}
,如果找不到匹配项,它将输出{x: undefined, y: undefined}
使用数组过滤器 ,请尝试:
function coordinates(id){ return nodes.filter(function(e){ return e.ID == id })[0] } var nodes=[{ID:"101",x:100,y:200},{ID:"102",x:200,y:200},{ID:"103",x:300,y:300},{ID:"104",x:200,y:300}]; var result = coordinates("103"); document.write("<pre>" + JSON.stringify(result, null, 3));
人们已经在这里提出了带有具体JavaScript的出色解决方案。 因此,我提出了另一个使用underscore.js的替代方法,以防您好奇。
function coordinates(id){
var n = _.findWhere(nodes, {ID: id});
return {x: n.x, y: n.y }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.