Selecting a 'property value' from an array based on another 'property value' in javascript -
i have array 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 have function takes node's id input , return (x,y). example, function coordinates(103)should read array (nodes) , return x = 300, y = 300 when it's called. pointer appreciated. :) have far. works i'd know neater , tidier methods.
function coordinates(id){ (var i=0 in nodes){ if(nodes[i].id == id){ return { x: nodes[i].x, y: nodes[i].y}; } } } console.log(coordinates(102));
basically you're looking @ 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} , if cannot find match output {x: undefined, y: undefined}
Comments
Post a Comment