Reputation: 832
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.
Upvotes: 1
Views: 86
Reputation: 760
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.
Upvotes: 0
Reputation: 2540
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.
Upvotes: 1
Reputation: 1524
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);
Upvotes: 1
Reputation: 529
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.
Upvotes: 1
Reputation: 11
data.filter(x => {
x.rows !== [];
});
You could filter the array.
Upvotes: -1