简体   繁体   中英

Javascript Filter Objects in Array and return Property of Object in Array of Object in Array

Im trying to Filter this Array:

var Zimmer = [{"Name":"F02A","Group":"Office","Devices":[
    {"Name":"F02A-1313.01","Device":"00265BE98E8C53","Type":"HmIP-WTH-B"},
    {"Name":"F02A-1315.03","Device":"00201BE9A13271","Type":"HmIP-eTRV-B"},
    {"Name":"F02A-1354.01","Device":"00119A499C1313","Type":"HmIP-eTRV-C"}
]},
{"Name":"F1","Group":"Office","Devices":[
    {"Name":"F1-1315.04","Device":"00201BE9A1381B","Type":"HmIP-eTRV-B"}
]},
{"Name":"F2","Group":"Klassenzimmer","Devices":[
    {"Name":"F2-1315.02","Device":"00201BE9A137E5","Type":"HmIP-eTRV-B"}
]},
{"Name":"F6","Group":"Office","Devices":[
    {"Name":"F6-1315.01","Device":"00201BE9A13290","Type":"HmIP-eTRV-B"}
]}]

And I want to output every Device with the Name F02A. example: 00265BE98E8C53 and than second output 00201BE9A13271.

For that I wrote the code

msg.payload = Zimmer.forEach(element => element.filter(name => name.Name = "F02A"));

Can somebody help?

You could take Array#flatMap and check if the name starts with the wanted part.

 const zimmer = [{ Name: "F02A", Group: "Office", Devices: [{ Name: "F02A-1313.01", Device: "00265BE98E8C53", Type: "HmIP-WTH-B" }, { Name: "F02A-1315.03", Device: "00201BE9A13271", Type: "HmIP-eTRV-B" }, { Name: "F02A-1354.01", Device: "00119A499C1313", Type: "HmIP-eTRV-C" }] }, { Name: "F1", Group: "Office", Devices: [{ Name: "F1-1315.04", Device: "00201BE9A1381B", Type: "HmIP-eTRV-B" }] }, { Name: "F2", Group: "Klassenzimmer", Devices: [{ Name: "F2-1315.02", Device: "00201BE9A137E5", Type: "HmIP-eTRV-B" }] }, { Name: "F6", Group: "Office", Devices: [{ Name: "F6-1315.01", Device: "00201BE9A13290", Type: "HmIP-eTRV-B" }] }], result = zimmer.flatMap(({ Devices }) => Devices.flatMap(({ Name, Device }) => Name.startsWith('F02A')? Device: []) ); console.log(result);

Using reduce method to loop through your array then check condition(check 'Name' is matched) each array, if your condition match then use map to make your devices to array, then concat to output

Zimmer.reduce((acc,data)=>{
    if(data.Name === "F02A"){
        acc = acc.concat(data.Devices.map((device)=>device.Device))
    }
    return acc
},[])

// output: ["00265BE98E8C53", "00201BE9A13271", "00119A499C1313"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM