// I have this kind of multiple object
_id: "5e5d00337c5e6a0444d00304"
orderID: 10355
orderDate: "2020-03-02"
user:
_id: "5e2e9699a648c53154f41025"
name: "xyz1"
email: "abcde@gmail.com"
mNumber: 12336
// and I want this in a single array
orderID: 10354, 10355
orderDate:"2020-03-02","2020-03-02"
name: "xyz", "xyz1"
email: "abcd@gmail.com", "abcde@gmail.com"
mNumber: 1234536, 12336
My main objective is to get the excel sheet where under these headers id name email and so on i get those data. like
orderID orderDate name email mNumber
10354 2020-03-02 xyz abcd@gmail.com 1234536
10355 2020-03-02 xyz1 abcde@gmail.com 12336
How should this be done in Angular?
If I understand you correctly, you can do something like this,
objs = [
{
_id: "5e5d00337c5e6a0444d00304",
orderID: 10354,
orderDate: "2020-03-02",
user:
{
_id: "5e2e9699a648c53154f41025",
name: "xyz",
email: "abcd@gmail.com",
mNumber: 1234536
}
},
{
_id: "5e5d00337c5e6a0444d00304",
orderID: 10355,
orderDate: "2020-03-02",
user:
{
_id: "5e2e9699a648c53154f41025",
name: "xyz1",
email: "abcde@gmail.com",
mNumber: 12336
}
}
];
const arr = [];
for (const o of objs) {
arr.push([
o.orderID,
o.orderDate,
o.user.name,
o.user.email,
o.user.mNumber
]);
}
console.log(arr);
This is the output,
[ [ 10354, '2020-03-02', 'xyz', 'abcd@gmail.com', 1234536 ],
[ 10355, '2020-03-02', 'xyz1', 'abcde@gmail.com', 12336 ] ]
Basically it is just an iteration.
I am going to add another solution. In this case, you don't want to describe all the values that goes in the row, but instead you want to describe the values you don't want in the row. You can use a recursive function to traverse the objects in this situation. fields
is the object where you describe wich values goes and witch don't. Something like this.
const fields = { _id: false, user: { _id: false} }
function toRowRec(obj, fields) {
let row = [];
const keys = Object.keys(obj);
for (const k of keys) {
if (!fields.hasOwnProperty(k)) {
row.push(obj[k]);
} else if (typeof obj[k] === 'object' && obj[k] !== null) {
row = row.concat(toRowRec(obj[k], fields[k]));
}
}
return row;
}
let arr = []
for (const o of objs) {
arr.push(toRowRec(o, fields));
}
console.log(arr);
I omit the input objs
(same as previous), and you will get the exact output than before.
You will see that I am also omitting the keys that I want to put in the row, to do this I am just checking if the key is in the fields
object.
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.