查找子陣的價值,我有兩個JavaScript對象:使用Javascript - 從另一個陣列
var classroom = {
"number" : "1",
"student" : [
{
"number" : 1,
"items" : [
{
"key" : "00000000000000000000001C",
"date" : "2016-04-21T17:35:39.997Z"
}
]
},
{
"number" : 2,
"items" : [
{
"key" : "00000000000000000000001D",
"date" :"2016-04-21T17:35:39.812Z"
},
{
"key" : "00000000000000000000002N",
"date" :"2016-04-21T17:35:40.159Z"
},
{
"key" : "00000000000000000000002Ñ",
"date" :"2016-04-21T17:35:42.619Z"
}
]
}
],
}
和
var items = [
{
"fields" : {
"tags" : [
{
"key" : "00000000000000000000001C",
"Batch" : "50",
"Bin" : "01",
"Tray" : "02"
},
{
"key" : "00000000000000000000002N",
"Batch" : "55",
"Bin" : "05",
"Tray" : "12"
},
{
"key" : "000000000000228510000032",
"Batch" : "12",
"Bin" : "12",
"Tray" : "01"
}
],
"Name" : "Rubber"
},
"_id" : "56d19b48faa37118109977c0"
},
{
"fields" : {
"tags" : [
{
"key" : "00000000000000000000001D",
"Batch" : "50",
"Bin" : "01",
"Tray" : "05"
},
{
"key" : "00000000000000000000002Ñ",
"Batch" : "52",
"Bin" : "07",
"Tray" : "02"
},
{
"key" : "221567010000000000000089",
"Batch" : "11",
"Bin" : "15",
"Tray" : "03"
}
],
"Name" : "Book"
},
"_id" : "56d19b48faa37118109977c1"
}
];
好吧,我需要創建一個貫穿各個item
每student
去功能在classroom
變量。對於每個item
,我需要在items
陣列中找到與tags
中的一個具有完全相同的key
的對象。
我的代碼也越來越奇怪的結果... missmatching項目...
var finalitems = [];
classroom.student.forEach(function (student){
student.items.forEach(function (obj){
items.forEach(function (theitem){
theitem.fields.tags.forEach(function (tag){
if (tag.key === obj.key) {
var newitem = theitem;
newitem.tag = obj;
finalitems.push(newitem);
}
});
});
});
});
我知道的foreach是一種指針,但我真的不明白爲什麼它正在奇怪,以及它如何需要被完成。
問候,
創建工作片段。定義「奇怪的結果」。 – Amit
https://jsfiddle.net/ynqtjL3d/請找出每件物品的標籤不是它應該是什麼。當應該有4個項目但每個具有不同的標籤密鑰(00000000000000000000001C,00000000000000000000001D,00000000000000000000002N,00000000000000000000002N)時,我可以看到4個項目(正確),但有兩個項目帶有標籤密鑰「00000000000000000000002Ñ」,另外兩個帶有標籤密鑰「00000000000000000000002N」 ) – Egidi
請添加結果應該如何。 –