简体   繁体   English

在过滤 object 内的深层嵌套数组时,保留父 object

[英]Keep parent object while filtering on deeply nested array within the object

I've searched SO for a solution to this but having a hard time applying any solutions given.我已经在 SO 中寻找解决方案,但很难应用任何给出的解决方案。 I'm using JavaScript/React so I need a solution in JS.我正在使用 JavaScript/React,所以我需要 JS 中的解决方案。

An object is returned from a data base with the following structure,从具有以下结构的数据库返回 object,

source.source.source (three levels, all children are called source). source.source.source(三个级别,所有的孩子都称为源)。

The first source is an object, the second source is also an object and the third source is an array with all the elements.第一个源是 object,第二个源也是 object,第三个源是包含所有元素的数组。

Each element in the array has a property, "isActive", as in数组中的每个元素都有一个属性“isActive”,如

source.source.source.isActive

I thought the below code would keep the entire object but it loses the two parent nodes and all that data (source, and source) and only returns the array nested within source.source.我认为下面的代码会保留整个 object,但它会丢失两个父节点和所有数据(源和源),并且只返回嵌套在 source.source 中的数组。 I need the entire returned object from axios filtered.我需要过滤从 axios 中返回的整个 object。

const responseDataFiltered = source.source.source.filter(obj => Boolean(obj.isActive) === true)

I need a way to keep all parent elements while only showing the array elements that have isActive === true.我需要一种方法来保留所有父元素,同时只显示具有 isActive === true 的数组元素。

What I am trying to achieve is to filter a response from a database where the returned elements have the property isActive set to true, and I need the main structure/parent elements.我想要实现的是过滤来自数据库的响应,其中返回的元素将属性 isActive 设置为 true,并且我需要主要结构/父元素。 So essentially, I need a copy of the main parent element source with it's nested data but filter out all isActive === false.所以本质上,我需要一个包含嵌套数据的主父元素源的副本,但过滤掉所有 isActive === false。

I am getting the data using Axios from an api.我正在使用 api 中的 Axios 获取数据。 The response is the entire object that has the deeply nested array with the thousands of elements I need to filter on isActive.响应是整个 object 具有深度嵌套的数组,其中包含我需要在 isActive 上过滤的数千个元素。 Once the returned object has filtered out all the isActive === false I want to pass it to a useState hook and display the data.一旦返回的 object 过滤掉了所有 isActive === false 我想将它传递给 useState 挂钩并显示数据。

You can just replace the nested array with the filter data:您可以将嵌套数组替换为过滤器数据:

 const source = { one: 1, two: 2, source:{ three: 3, four: 4, source: [ {isActive: true}, {isActive: true}, {isActive: false}, {isActive: false}, ], }, }; const actives = source.source.source.filter(({ isActive }) => isActive); const responseDataFiltered = {...source, source: {...source.source, source: actives, }, }; console.log(responseDataFiltered);
 .as-console-wrapper { max-height: 100%;important: top 0 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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