我正在嘗試從我的資料集中搜索下面列出的每個物件,以查看它們是否包含值以及它們是否具有該值以將整個物件添加到新陣列中。
例子:
在物件串列中搜索資料“連續”,如果該資料存在(在 Doormerica 和 Hager 中會這樣做),則獲取整個物件“Doormerica”和“Hager”并將整個物件放入一個新陣列中。
{
"Doormerica": {
"Floor Stops": [],
"Overhead Stop": [],
"Pull": [],
"Chain Stop": [],
"Continuous": [
"ALX",
"AL",
"QR"
],
"Kick": [],
"Back to Back Pull": [],
"Concealed": [],
"Butt": [],
"Surface Mount": [],
"Mop": [],
"Armor": [],
"Push": [],
"Wall Stops": []
},
"Schlage": {
"Mortise": [],
"Cylindrical": [
"ALX",
"AL",
"QR"
],
"Deadbolt": [],
"Dummy": [],
"Interconnected": [],
"Cylinders": []
},
"Pemko": {
"Sweeps": [
"345AV"
],
"Permiter Seal": [
"303AS"
],
"Thresholds": [
"170A"
],
"Rain Drip": [
"346C"
],
"Astragal": []
},
"LCN": {
"Surface Mount": [
"4040XP"
],
"Concealed": []
},
"Hager": {
"Butt": [],
"Continuous": []
}
}
uj5u.com熱心網友回復:
資料轉換
我決定發布此解決方案,因為問題詢問如何“獲取整個物件”。并且在結果中包含名稱(Doormerica、Hager 等),無論是作為鍵還是值,似乎都是轉換的重要部分。我們可以使用Object.entries()、Array.reduce()、Spread Syntax和適當的轉換代碼一次性完成此操作。
兩種轉換的示例
[{"Doormerica": { "Floor Stops": [], ...}] // name as a key
[{ "Name": "Doormerica", "Floor Stops": [], ...}] // name as a value
片段
該片段顯示了進行這兩種轉換的完整代碼。
const data = {Doormerica:{"Floor Stops":[],"Overhead Stop":[],Pull:[],"Chain Stop":[],Continuous:["ALX","AL","QR"],Kick:[],"Back to Back Pull":[],Concealed:[],Butt:[],"Surface Mount":[],Mop:[],Armor:[],Push:[],"Wall Stops":[]},Schlage:{Mortise:[],Cylindrical:["ALX","AL","QR"],Deadbolt:[],Dummy:[],Interconnected:[],Cylinders:[]},Pemko:{Sweeps:["345AV"],"Permiter Seal":["303AS"],Thresholds:["170A"],"Rain Drip":["346C"],Astragal:[]},LCN:{"Surface Mount":["4040XP"],Concealed:[]},Hager:{Butt:[],Continuous:[]}};
let subset = Object.entries(data).reduce((a,v) =>
v[1].hasOwnProperty("Continuous") ? [...a, {[v[0]]: v[1]} ] : a
// alternative methods adds a name property
// v[1].hasOwnProperty("Continuous") ? [...a, {Name: v[0], ...v[1]} ] : a
, []);
console.log(subset);
uj5u.com熱心網友回復:
所以我們遍歷物件的值,在每個值 = 物件上搜索我們的“術語”。要搜索物件的屬性,您只需要檢查是否obj[property]存在。
var obj = {Doormerica:{"Floor Stops":[],"Overhead Stop":[],Pull:[],"Chain Stop":[],Continuous:["ALX","AL","QR"],Kick:[],"Back to Back Pull":[],Concealed:[],Butt:[],"Surface Mount":[],Mop:[],Armor:[],Push:[],"Wall Stops":[]},Schlage:{Mortise:[],Cylindrical:["ALX","AL","QR"],Deadbolt:[],Dummy:[],Interconnected:[],Cylinders:[]},Pemko:{Sweeps:["345AV"],"Permiter Seal":["303AS"],Thresholds:["170A"],"Rain Drip":["346C"],Astragal:[]},LCN:{"Surface Mount":["4040XP"],Concealed:[]},Hager:{Butt:[],Continuous:[]}};
function my_search(obj, term) {
return Object.values(obj).reduce(function(agg, value) {
if (value[term]) {
agg.push(value)
}
return agg;
}, [])
}
console.log(my_search(obj, "Continuous"))
.as-console-wrapper {max-height: 100% !important}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/520850.html
