I have this array of objects and I want to get all the controls
from this to another array:
this.formModel = {
sections: [
{
title: 'Section 01',
controls: [
new FormControlInput({
key: 'name 01',
label: 'Name 01'
}),
new FormControlSelect({
key: 'abc',
label: 'Abc'
})
]
},
{
title: 'Section 02',
controls: [
new FormControlInput({
key: 'name 02',
label: 'Name 02'
})
]
}
]
};
I am using map
for this but I am not getting single array, I am getting array of arrays:
this.formModel.sections.map(function (x) { return x.controls; })
Getting this:
[
{
[{
key: 'name 01',
label: 'Name 01'
},
{
key: 'abc',
label: 'Abc'
}]
},
{
[{
key: 'name 02',
label: 'Name 02'
}]
}
]
What I want is this:
[
{
key: 'name 01',
label: 'Name 01'
},
{
key: 'abc',
label: 'Abc'
},
{
key: 'name 02',
label: 'Name 02'
}
]
You just need to flatten your array after mapping:
var obj = { sections: [{ title: 'Section 01', controls: [ { key: 'name 01', label: 'Name 01' }, { key: 'abc', label: 'Abc' } ] }, { title: 'Section 02', controls: [ { key: 'name 02', label: 'Name 02' } ] } ] }; var mapped = obj.sections.map(function (x) { return x.controls; }); var flattened = [].concat.apply([], mapped); console.log(flattened);
To simplify your example:
// This is your structure: var sections= [{ controls: [{}, {}] // C1 }, { controls: [{}] // C2 } ]; // With the map, grabbing each `controls` property, and using that as an entry in your array: var mapped = sections.map(function (x) { return x.controls; }); console.log(mapped); // [[{},{}],[{}]] // ^ C1 ^ C2 // We need to remove that extra layer of arrays: var flattened = [].concat.apply([], mapped); console.log(flattened);
You can use reduce
to flatten the hierarchy
formModel.sections
.map(x => x.controls)
.reduce((prev, current) => prev.concat(current), [])
Use reduce
instead of map
:
let formModel = { sections: [ { title: 'Section 01', controls: [ { key: 'name 01', label: 'Name 01' }, { key: 'abc', label: 'Abc' } ] }, { title: 'Section 02', controls: [ { key: 'name 02', label: 'Name 02' } ] } ] }; let result = formModel.sections.reduce((res, section) => { return res = res.concat(section.controls); }, []); console.log(result);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.