我有一个名为collection
的数组。此数组包含大量长度为12的数组。后一个数组中的每个项目都包含源ID [0]和目标ID [1](源和目标对是唯一的,但是相同的源可以将ID分配给不同的目标ID)。
给定源ID和目标ID,我需要找到具有给定ID的数组内的项并操纵其值。
jQuery存在,如果这有助于找到解决方案。
提前致谢!
var collection = [
[
136898,
162582,
"8X1ABG\1",
"lorem ipsum",
true,
"FULL",
true,
"FULL",
"8X1ABG\0",
"dolor sit",
false,
"SIMILAR"
],
[
136898,
163462,
"8X1ABG\1",
"lorem ipsum",
true,
"FULL",
true,
"FULL",
"8X1ABG\0",
"dolor sit",
false,
"SIMILAR"
],
[
136578,
161873,
"8X1A1G\2",
"lorem ipsum",
true,
"FULL",
true,
"FULL",
"8X1A1G\0",
"dolor sit",
false,
"SIMILAR"
],
[
136432,
162280,
"8X1ABC\1",
"lorem ipsum",
true,
"FULL",
true,
"FULL",
"8X1ABC\0",
"dolor sit",
false,
"SIMILAR"
]]
// TODO: find the unique item in collection array with the following source
// and target ID
var sourceId = 136898;
var targetId = 163462;
// TODO: update some values of the identified item inside collection
答案 0 :(得分:3)
试试这个:
var item = collection.filter(function(collect) {
return collect[0] == sourceId && collect[1] == targetId;
});
同样,就像我在评论中所说的那样,如果你将数据结构更改为具有命名键的对象数组会更好,那么你可以更加可读:
return collect.sourceId == sourceId && collect.targetId == targetId;
答案 1 :(得分:1)
如果您需要兼容旧版浏览器,因为.filter()
为supported only by IE9,您还可以循环遍历数组的元素(或编写MDN提供的过滤器实现)。
var item = [];
for (var i = 0; i < collection.length; i++) {
var coll = collection[i];
if (coll[0] == sourceId && coll[1] == targetId) item.push(coll);
}