我有两个 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"
}
];
好的,我需要创建一个函数来遍历 classroom
变量中每个 student
的每个 item
。对于每个 item
,我需要在 items
数组中找到在其 tags< 之一中具有完全相同
.key
的对象
我的代码得到奇怪的结果...不匹配的项目...
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 是一种指针,但我不太明白为什么它工作得很奇怪以及应该如何完成。
问候,
最佳答案
javascript变量只保存对象引用,而不是内存中的实际对象,所以这一行:
var newitem = theitem;
意味着newitem引用与item相同的对象,而不是从item创建新对象。
所以
newitem.tag = obj;
与
相同theitem.tag = obj;
这意味着您正在修改输入对象,这就是您无法获得预期输出的原因。
要获得所需的行为,您需要创建该项目的副本并将该对象分配给 newitem 变量:
var newitem = Object.create(theitem);
关于Javascript - 通过另一个数组中的值在子数组中查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36777800/