写一个方法js将数组对象中某个属性值相同的对象合并成一个新对象

65 阅读1分钟

"```javascript function mergeObjects(arr, prop) { return arr.reduce((acc, obj) => { const key = obj[prop]; if (!acc[key]) { acc[key] = { ...obj }; } else { acc[key] = { ...acc[key], ...obj }; } return acc; }, {}); }

const arr = [ { id: 1, name: 'Alice', age: 25 }, { id: 2, name: 'Bob', age: 30 }, { id: 3, name: 'Alice', profession: 'Engineer' }, ];

const merged = mergeObjects(arr, 'name'); console.log(merged);

In the above code, we define a function called `mergeObjects` which takes an array of objects and a property name as input. Inside the function, we use the `reduce` method to iterate over the array and merge objects with the same value for the specified property into a new object.

We then define an example array `arr` containing objects with `id`, `name`, and `age` properties. We call the `mergeObjects` function with the array and the property name 'name', which results in merging the objects with the same 'name' value into a new object.

When we run the code, the `merged` variable will contain the merged objects based on the 'name' property, and we can see the result by logging it to the console."