[英]Selecting a 'property value' from an array based on another 'property value' in javascript
I have an array like this. 我有这样的数组。
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}];
I'd like to have a function which takes node's ID as input and return its (x,y). 我想要一个函数,该函数将节点的ID作为输入并返回其(x,y)。 For example, the function coordinates(103)
should read the array (nodes) and return x = 300, y = 300 when it's called. 例如,函数coordinates(103)
应该读取数组(节点)并在调用时返回x = 300,y = 300。 Any pointer is appreciated. 任何指针表示赞赏。 Thanks :) This is what I have so far. 谢谢:)这就是我到目前为止。 It works but I'd like to know neater and tidier methods. 它有效,但是我想知道更整洁的方法。
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));
See comments inline: 查看内联评论:
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);
You can use .filter
, like so 您可以像这样使用.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));
basically you're looking at something like this 基本上你在看这样的东西
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};
};
then f('101')
outputs {x: 100, y:200}
and if cannot find a match then it will output {x: undefined, y: undefined}
然后f('101')
输出{x: 100, y:200}
,如果找不到匹配项,它将输出{x: undefined, y: undefined}
Using array filter , Try: 使用数组过滤器 ,请尝试:
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));
Brilliant solutions with concrete JavaScript have already been proposed by people here. 人们已经在这里提出了带有具体JavaScript的出色解决方案。 So I propose another alternative using underscore.js , just in case you're curious. 因此,我提出了另一个使用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.