[英]Filter a javascript tree without mutating the original array
I'm working on a react project where I need to filter an array of objects without mutating the original array 我正在一个反应项目中,我需要过滤对象数组而不改变原始数组
const array = [{ name: 'bar', children: [{ name: 'foo', children: [{ name: 'baz123', }, { name: 'baz', }] }] }, { name: 'shallowKey' }, { name: 'abc' }];
For example, I want to only filter the concerned object and its children. 例如,我只想过滤有关的对象及其子对象。
This is the jsfiddle 这是jsfiddle
function filterData(data) {
var r = data.filter(function(o) {
if (o.children) o.children = filterData(o.children);
return o.name.length === 3;
})
return r;
}
I tried that function from a stackoverflow question, but is there a way to use that same functionality without mutating the data. 我从stackoverflow问题中尝试了该功能,但是有一种方法可以使用相同的功能而不会导致数据突变。 Thanks
谢谢
Array .filter()
already creates a new array, you just need to fix the part where the o.children
is mutated. Array
.filter()
已经创建了一个新数组,您只需要修复o.children
被突变的部分。 To do that you could use .map()
and simply copy all fields using Object.assign()
or object spread and just assign children
as the result passed through the same filter function: 为此,您可以使用
.map()
并使用Object.assign()
或对象散布简单地复制所有字段,然后仅将children
分配为通过同一过滤器函数传递的结果:
function filterData(data) {
return data
.filter(obj => obj.name.length === 3) // filter array first
.map(obj => ({ // then re-map to new objects
...obj, // copy shallow fields
children: obj.children && filterData(obj.children) // filter children
}));
}
如果对象中没有任何原型或函数,一种简单的复制方法是将原始字符串化并将其解析回对象
var r= JSON.parse(JSON.stringify(data)).filter(...
You can create a copy of your original array using a spread operator or Object.assign()
function. 您可以使用传播运算符或
Object.assign()
函数创建原始数组的副本。
const arrayCopy= [...array] //spread operator
const arrayCopy = Object.assign({}, array);
Otherwise as Aaron suggested, using filter()
, map()
, reduce()
function always returns a new array without mutating your original array. 否则,如Aaron所建议的那样,使用
filter()
, map()
, reduce()
函数始终返回一个新数组,而不会更改您的原始数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.