我在使用時遇到了一些問題.map,.filter我無法獲得兩個物件中不相似的物件。我需要做哪些更改才能從arrayObjTwo.
代碼
const arrayObjOne = [{
countryCode: "US",
description: " Backyard of home",
id: "1234",
location: "US",
name: "Backyard",
}]
// Array Object 2
const arrayObjTwo =[
{ description: "Backyard of home", spaceName: "Backyard" },
{ description: "Frontyard of home", spaceName: "Frontyard"},
]
const object1Names = arrayObjOne.map(obj => obj.Name); // for caching the result
const results = arrayObjTwo.filter(name => !object1Names.includes(name));
console.log(results);
一種編譯器代碼:https ://onecompiler.com/javascript/3xy92hpmp
預期結果:
const arrayObjTwo =[
{ description: "Frontyard of home", spaceName: "Frontyard" }
]
謝謝..
uj5u.com熱心網友回復:
您對結果的過濾器是錯誤的。您應該使用“object.spaceName”而不是“name”,因為您正在回圈遍歷物件陣列而不僅僅是字串
// So this line:
const results = arrayObjTwo.filter(name => !object1Names.includes(name));
// Should be:
const results = arrayObjTwo.filter(object => !object1Names.includes(object.spaceName));
// And you have a typo:
const object1Names = arrayObjOne.map(obj => obj.Name);
// Should be like so as keys and properties are case-sensitive:
const object1Names = arrayObjOne.map(obj => obj.name);
所以這應該是:
const arrayObjOne = [{
countryCode: "US",
description: " Backyard of home",
id: "1234",
location: "US",
name: "Backyard",
}]
// Array Object 2
const arrayObjTwo =[
{ description: "Backyard of home", spaceName: "Backyard" },
{ description: "Frontyard of home", spaceName: "Frontyard"},
]
const object1Names = arrayObjOne.map(obj => obj.name); // for caching the result
const results = arrayObjTwo.filter(object => !object1Names.includes(object.spaceName));
console.log(results);
uj5u.com熱心網友回復:
你很近!
您的地圖陳述句中的名稱已大寫,但 javascript 區分大小寫,因此您正在查找“名稱”的欄位不存在,因此您的“object1Names”回傳未定義。
您應該查找 obj.name
您還需要將其與 arrayObjTwo 的“spaceName”欄位進行比較,而不是整個物件。
這是您的代碼進行了這些小改動:
const arrayObjOne = [{
countryCode: "US",
description: " Backyard of home",
id: "1234",
location: "US",
name: "Backyard",
}]
// Array Object 2
const arrayObjTwo =[
{ description: "Backyard of home", spaceName: "Backyard" },
{ description: "Frontyard of home", spaceName: "Frontyard"},
]
const object1Names = arrayObjOne.map(obj => obj.name); // for caching the result
const results = arrayObjTwo.filter(obj => !object1Names.includes(obj.spaceName));
console.log(results);
uj5u.com熱心網友回復:
你需要這個嗎?
const arr1 = [{
countryCode: "US",
description: " Backyard of home",
id: "1234",
location: "US",
name: "Backyard",
}]
// Array Object 2
const arr2 =[
{ description: "Backyard of home", spaceName: "Backyard" },
{ description: "Frontyard of home", spaceName: "Frontyard"},
]
const names = arr1.map(item => item.name); // for caching the result
console.log(names);
const res = arr2.filter(item => !names.includes(item.name));
console.log(res);
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/456291.html
標籤:javascript
上一篇:基于兩個布爾條件的js陣列過濾器
