Javascript JS嵌套reduce
问题是如何迭代对象数组,并从关键选项(同样是对象数组)的值中仅选择那些具有Javascript JS嵌套reduce,javascript,frontend,reduce,Javascript,Frontend,Reduce,问题是如何迭代对象数组,并从关键选项(同样是对象数组)的值中仅选择那些具有is_enabled=true的对象 以下是我正在查看的数据结构: [ { 'id': 1, 'label': 'Label1', 'options': [ { 'id': 1.1, 'label': 'Label1.1', 'is_enabled'
is_enabled=true
的对象
以下是我正在查看的数据结构:
[
{
'id': 1,
'label': 'Label1',
'options': [
{
'id': 1.1,
'label': 'Label1.1',
'is_enabled': true
},
{
'id': 1.2,
'label': 'Label1.2',
'is_enabled': false
},
],
},
{
'id': 2,
'label': 'Label2',
'options': [
{
'id': 2.1,
'label': 'Label2.1',
'is_enabled': false
},
{
'id': 2.2,
'label': 'Label2.2',
'is_enabled': false
},
],
},
{
'id': 3,
'label': 'Label3',
'options': [
{
'id': 3.1,
'label': 'Label3.1',
'is_enabled': true
},
{
'id': 3.2,
'label': 'Label3.2',
'is_enabled': true
},
],
},
]
这是我想要的结果:
[
{
'id': 1,
'label': 'Label1',
'options': [
{
'id': 1.1,
'label': 'Label1.1',
'is_enabled': true
},
],
},
{
'id': 3,
'label': 'Label3',
'options': [
{
'id': 3.1,
'label': 'Label3.1',
'is_enabled': true
},
{
'id': 3.2,
'label': 'Label3.2',
'is_enabled': true
},
],
},
]
提前感谢您可以使用
reduce
并在其回调中使用filter
获取选项
数组,其中启用的是
let数据=[{
“id”:1,
“标签”:“标签1”,
“选项”:[{
“id”:1.1,
“标签”:“标签1.1”,
“是否已启用”:true
},
{
“id”:1.2,
“标签”:“标签1.2”,
“是否已启用”:false
},
],
},
{
“id”:2,
“标签”:“标签2”,
“选项”:[{
“id”:2.1,
“标签”:“标签2.1”,
“是否已启用”:false
},
{
“id”:2.2,
“标签”:“标签2.2”,
“是否已启用”:false
},
],
},
{
"id":3,,
“标签”:“标签3”,
“选项”:[{
“id”:3.1,
“标签”:“标签3.1”,
“是否已启用”:true
},
{
“id”:3.2,
“标签”:“标签3.2”,
“是否已启用”:true
},
],
},
];
const newData=data.reduce((acc,curr)=>{
//获取'is_enabled'为true的选项
const getEnabledArr=curr.options.filter(item=>item.is_enabled);
如果(getEnabledArr.length>0){
const newVal=Object.assign({},curr{
选项:getEnabledArr
});
acc.push(新瓦尔)
}
返回acc;
}, []);
console.log(newData)
您可以使用map
这样做:
var数据=[{'id':1,'label':'Label1','options':[{'id':1.1,'Label1.1','is_enabled':true},{'id':1.2,'Label1.2','is_enabled':false},,},{'id':'Label2','options':[{'id':2.1,'Label2.1','is_enabled':false},{'id':2.2,'Label2''is",},},{'id':3,'label':'Label3','options':[{'id':3.1,'label':'Label3.1','is_enabled':true},{'id':3.2,'label':'Label3.2','is_enabled':true},],};
var result=data.map(({options,…rest})=>({…rest,options:options.filter(val=>val.is_enabled)});
console.log(结果);
//数据是您的初始数据
数据减少((acc,obj)=>{
const enabledOptions=obj.options.filter(option=>option.is_enabled);
if(enabledOptions.length!==0){
加速推({
…obj,
选项:启用选项
});
}
返回acc;
}, []);
您是否尝试自己解决此问题?请发布一些代码并解释它的问题所在。