似乎无法使其正常工作。我有两个数组,我想在数组 1 和 2 之间找到匹配项。array2
匹配的结果应该存储在数组变量 tobechanged
中。
我可以找到 array1
和 array3
之间的匹配项,但似乎无法以正确的方式获取 array2
的 ID。
var array1 = ["279482", "100"];
var array2 = [{id: "279482", stock: "9"},{id: "213", stock: "2"}];
var array3 = ["279482", "213"];
var tobechanged = [];
// Loop for array1
for(let i = 0; i < array1.length; i++) {
// Loop for array2
for(let j = 0; j < array2.length; j++) {
// Compare the element of each and
// every element from both of the
// arrays
if(array1[i] === array2[j].id) { //how to compare id of array2?
console.log("match");
// Return if common element found
//console.log([{id: array2[j].id, stock: array2[j].stock}); //how to get the result in a proper array?
}
}
}
答案 0 :(得分:1)
您可以通过使用 includes
查看另一个对象来过滤该对象。
const
array1 = ["279482", "100"],
array2 = [{ id: "279482", stock: "9" }, { id: "213", stock: "2" }],
tobechanged = array2.filter(o => array1.includes(o.id));
console.log(tobechanged);
答案 1 :(得分:0)
你可以在循环中添加一个 push() 方法,
var array1 = ["279482", "100"];
var array2 = [{id: "279482", stock: "9"},{id: "213", stock: "2"}];
var tobechanged = [];
for(let i = 0; i < array1.length; i++) {
for(let j = 0; j < array2.length; j++) {
if(array1[i] === array2[j].id) {
console.log("match");
tobechanged.push(array2[j].id); //or tobechanged.push(array1[i]);
}
}
}
console.log(tobechanged);