![](/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.