为何JS中filter返回新数组仍修改原list?如何避免修改原变量?
How to Fix It: Avoid Mutating Original Objects
To achieve your goal without altering the original list, you need to create copies of the objects (and their arr properties) before modifying them. Here are two clean, practical approaches:
Approach 1: Copy Objects First, Then Merge
First, filter the target topic elements, then create shallow copies of each object (since your arr contains primitive values, a shallow copy is sufficient):
var list = [{topic : "fussball", arr : [1,2]}, {topic : "soccer", arr : [3,4]}, {topic : "fussball", arr : [5,6]},{topic : "soccer", arr : [7,8]}]; function someFilterMethod(list, topic){ // Filter matching objects and create copies (with a new arr array) let tops = list.filter(obj => obj.topic === topic) .map(obj => ({ ...obj, arr: [...obj.arr] // Create a copy of the original arr })); // Merge the copied objects' arr properties for(let i = 0; i < tops.length; i++){ for(let j = i + 1; j < tops.length; j++){ tops[i].arr.push(...tops[j].arr); tops.splice(j, 1); j--; // Adjust index after splice to avoid skipping elements } } return tops; } var a = someFilterMethod(list, "fussball"); console.log(a); // [{ topic: "fussball", arr: [1,2,5,6] }] console.log(list); // Original array remains unchanged!
Approach 2: Use reduce for Cleaner, More Efficient Merging
A more streamlined way is to use Array.reduce() to group and merge elements in one pass, while creating copies along the way:
var list = [{topic : "fussball", arr : [1,2]}, {topic : "soccer", arr : [3,4]}, {topic : "fussball", arr : [5,6]},{topic : "soccer", arr : [7,8]}]; function someFilterMethod(list, topic){ return Object.values( list.filter(obj => obj.topic === topic) .reduce((accumulator, currentObj) => { // Create a new entry if this topic isn't already tracked if (!accumulator[currentObj.topic]) { accumulator[currentObj.topic] = { topic: currentObj.topic, arr: [...currentObj.arr] }; } else { // Merge the arr into the existing copied object accumulator[currentObj.topic].arr.push(...currentObj.arr); } return accumulator; }, {}) ); } var a = someFilterMethod(list, "fussball"); console.log(a); // [{ topic: "fussball", arr: [1,2,5,6] }] console.log(list); // Original array stays intact
Both approaches ensure that you're only modifying copies of the original objects, so your list variable remains unaltered.
内容的提问来源于stack exchange,提问作者user2069136
相关产品推荐
相关产品推荐

