我有一個可以具有任意長度和任意深度的對象數組。我需要能夠通過它的id找到一個對象,然後修改該數組中的對象。有沒有一種有效的方法來做到這一點與lodash或純js?在javascript數組中查找並修改深度嵌套對象
以爲可以創建索引,導致了對象但構建表達與這些索引訪問該對象似乎過於複雜/不必要
EDIT1的陣列;感謝所有你的答覆,我會盡力而且更具體。我目前正在找到我想要修改的對象的位置。父母是目標對象每個父母的ID數組。祖先可能是這個陣列的一個更好的名字。 costCenters是包含我想要修改的對象的對象數組。此功能遞歸,並返回指標,導致我想修改
var findAncestorsIdxs = function(parents, costCenters, startingIdx, parentsIdxs) {
var idx = startingIdx ? startingIdx : 0;
var pidx = parentsIdxs ? parentsIdxs : [];
_.each(costCenters, function(cc, ccIdx) {
if(cc.id === parents[idx]) {
console.log(pidx);
idx = idx + 1;
pidx.push(ccIdx);
console.log(pidx);
pidx = findAncestorsIdx(parents, costCenters[ccIdx].children, idx, pidx);
}
});
return pidx;
};
現在有了這個數組索引如何定位和修改確切的對象我想要的對象的數組?我已嘗試這其中的祖先是索引的陣列,costCenters是與所述對象的數組修改和父是新值將被分配給所述目標對象
var setParentThroughAncestors = function(ancestors, costCenters, parent) {
var ccs = costCenters;
var depth = ancestors.length;
var ancestor = costCenters[ancestors[0]];
for(i = 1; i < depth; i++) {
ancestor = ancestor.children[ancestors[i]];
}
ancestor = parent;
console.log(ccs);
return ccs;
};
這顯然只是返回未修改costCenters數組,所以我可以看到的唯一另外一種方式是構造像myObjects [idx1] .children [2] .grandchildren [3] .ggranchildren [4] .something = newValue這樣的表達式。這是唯一的方法嗎?如果是的話,那麼最好的辦法是什麼?
你必須對所有對象遞歸遍歷和比較對您正在尋找的ID。 – 2014-08-29 13:28:23
你說你有一個對象數組。 JavaScript中的數組是索引的,而不是關聯的,所以大概你的意思是通過它的索引找到一個對象,而不是ID。否則,請澄清。 – Utkanos 2014-08-29 13:28:42
數組中的每個對象都有一個唯一的ID。我想通過該ID找到給定的對象,然後更改該對象 – Ir1sh 2014-08-29 13:33:16