data = [
{
rows: [
{ name: 'a'}
]
},
{
rows: [
{ name: 'b'}
]
}
{
rows: []
}
]
what I'm trying to do here is to get the rows data. which is like this.
expected output:
data = [
{
name: 'a'
},
{
name: 'b'
}
];
where it will remove the empty array and it will merge on it.
You can use reduce on your array as below -
var data = [ { rows: [ { name: 'a'} ] }, { rows: [ { name: 'b'} ] }, { rows: [] } ] var reducedSet = []; data.reduce((accumulator, currentValue, currentIndex) => { var currentRows = currentValue.rows; var rowLength = currentRows && currentRows.length if (rowLength) { for (i = 0; i < rowLength; i++) { accumulator.push(currentRows[i]); } return accumulator; } }, reducedSet); console.log(reducedSet);
Alternatively, you can also do it as below -
var data = [ { rows: [ { name: 'a'} ] }, { rows: [ { name: 'b'} ] }, { rows: [] } ]; var result = data.filter(f => f.rows && f.rows.length && f.rows.length > 0).map((currentValue) => { return currentValue.rows; }).flat(); console.log(result);
Above code first filters out the empty rows and then maps the out the data and finally flattens the result.
data = [ { rows: [ { name: 'a'}, ] }, { rows: [ { name: 'b'}, ] }, { rows: [] } ] let mappedData = data.map(obj => { return obj.rows.map(obj2 => { return { name: obj2.name } }) }) mappedData = mappedData.flat() console.log(mappedData)
Try something like that, I guess that's what you want from what I've seen.
This might help. The solution provided takes into account that there might be multiple name
inside a single rows
.
let data = [] // YOUR OBJECT IN THE QUESTION
let data2: any = []
data.forEach(el => {
if(el.rows.length > 0) {
data2 = [...data2, ...el.rows];
}
})
console.log('data2', data2);
If you want to one-line it with modern Javascript, this is the way.
const transform = (inData) => inData.reduce((outData, { rows }) => outData.concat(rows), []);
Basically, create a new array, then for each entry in inData extract the content of the rows
property and add it to the array.
data.filter(x => {
x.rows !== [];
});
You could filter the array.
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.