ネストされた配列でスプライスメソッドを一般的な方法で使うのに問題があります。 だから、 "filterArray"にオブジェクトの参照がない場合、 "bigArray"の "nestedArray"のオブジェクトを削除します。ネストされた配列内のマッチしないオブジェクトを削除する
私は自分がしたいことの例を作りました。 あなたは私がネイティブのjavascriptやLodashでそれを改善する方法についての解を得たら、自由に入力してください。私は本当に立ち往生している。
期待される結果は次のようになります。
sort.unsortedArray = { "bigArray" : [
{"id": 1, "text" : "This should be visible when done",
"nestedArray": [
{ "id": 2, "nestedText": "Sort me out!" }
]
},
{ "id": 2, "text" : "This should be visible when done",
"nestedArray": [
{ "id": 2, "nestedText": "This one should be visible in the coming array" }
]
}]}
Here'sそのためcodepen。
var sort = this;
var init = function(){
sort.outObjects();
};
sort.filterArray = { "filter" : [
{ "id": 3, "groupId": 1 },
{ "id": 2, "groupId": 2 }]};
sort.unsortedArray = { "bigArray" : [
{"id": 1, "text" : "This should be visible when done",
"nestedArray": [
{ "id": 1, "nestedText":"Sort this one out!" },
{ "id": 2, "nestedText": "Sort me out!" },
{ "id": 3, "nestedText": "This one should be visible in the coming array"}]},
{ "id": 2, "text" : "This should be visible when done",
"nestedArray": [
{ "id": 1, "nestedText": "Sort me out!" },
{ "id": 2, "nestedText": "This one should be visible in the coming array" },
{"id": 3, "nestedText": "Sort this one out!" }]}
]},
sort.outObjects = function(){
//Check that we got the objects in same scope
if(sort.filterArray && sort.unsortedArray){
//Loop through "bigArray" object
for(var i = 0; i< sort.unsortedArray.length; i++){
console.log("sort.unsortedArray.length : ", sort.unsortedArray.length);
//Loop through each "nestedArray":s objects
for(var j = 0; j< sort.unsortedArray[i].nestedArray.length; j++){
console.log("sort.unsortedArray[i].nestedArray.length : ", sort.unsortedArray[i].nestedArray.length);
//Loop through filterArray object and compare each object in nested array, if they dont match, delete them.
for(var k = 0; k< sort.filterArray.length; k++){
console.log("sort.filterArray.length : ", sort.filterArray.length);
if(sort.filterArray[k].id != sort.unsortedArray[i].nestedArray[j].id){
//Delete unmatching object from unsortedArray
sort.unsortedArray[i].nestedArray.splice(j,1);
console.log("sort.unsortedArray after splice : ", sort.unsortedArray);
}
}
}
}
}
else{
console.log("Missing connection to object",sort.filterArray, sort.unsortedArray);
}
}
init();
filterArray "dosen'tは、オブジェクトの参照を持っている "" 場合" とは何を意味するのですか? '' bigArray "'は 'groupId'というプロパティを持つオブジェクトを持っていません – RomanPerekhrest
@RomanPerekhrest、まさに!それは私が直面している問題です。 bigArrayオブジェクトへの唯一の参照です。 –
OK、どのように期待した結果を表示する必要がありますか? – RomanPerekhrest