如何使用AngularJS合并JavaScript数组及关联设备与外设对象
Hey there! Let's break down your two questions step by step, since both are about combining data in AngularJS/JavaScript:
1. Using AngularJS to Merge Two JavaScript Arrays
AngularJS comes with handy utility functions to handle array merging—here are two reliable approaches:
- Option 1: Combine
angular.copy()with nativeconcat()
If you want a brand new merged array without modifying the original ones, start by copying one array, then useconcat()to append the other:
const arr1 = [1, 2, 3]; const arr2 = [4, 5, 6]; // Creates a new merged array; original arrays stay untouched const mergedArr = angular.copy(arr1).concat(arr2); // Result: [1, 2, 3, 4, 5, 6]
- Option 2: Use
angular.merge()angular.merge()merges the second array into the first (this modifies the original target array). If you don't want to alter the original, pass an empty array as the initial target:
const arr1 = [1, 2, 3]; const arr2 = [4, 5, 6]; // Modifies arr1 directly angular.merge(arr1, arr2); // arr1 now becomes: [1, 2, 3, 4, 5, 6] // To keep original arrays intact: const mergedArr = angular.merge([], arr1, arr2);
2. Merging Device and Peripheral Arrays (One-to-Many Relationship)
Since a single device can have multiple peripherals, we'll add a peripherals property to each device object and populate it with the matching peripherals (your example has one device, but I'll also note how to handle multiple devices).
Here's the code using your sample data:
// Your original data const device = [{ devHardwareId: "40A8F065E465", deviceId: 67, deviceIp: "192.168.2.3", deviceName: "DESKTOP-IV0H659" }]; const peripherals = [{ peripheralId: 3, perHardwareId: "AVtech-Cam", peripheralName: "BackGate", peripheralType: "Video", isActive: true }, { peripheralId: 1, perHardwareId: "Logitech-Cam", peripheralName: "FrontCam", peripheralType: "Video", isActive: true }]; // Merge: Add peripherals to the device (copy first to avoid modifying original data) const mergedDevice = angular.copy(device[0]); mergedDevice.peripherals = angular.copy(peripherals); // For multiple devices (match by a shared identifier, e.g., hardware ID): // const mergedDevices = device.map(dev => { // // Filter peripherals that belong to this device // const matchedPeripherals = peripherals.filter(per => // /* Add your matching logic here, e.g., per.devHardwareId === dev.devHardwareId */ // ); // return angular.merge({}, dev, { peripherals: matchedPeripherals }); // }); console.log(mergedDevice);
After running this, mergedDevice will include all the original device properties plus a peripherals array containing all your peripheral data.
内容的提问来源于stack exchange,提问作者Tharuka
相关产品推荐
相关产品推荐

