Home > Mobile >  Proccessing nested object in an array of objects?
Proccessing nested object in an array of objects?

Time:02-02

I have the following array of object.

enter image description here

Each object has a nested team object, from which I want to take the value of the team.name and add to parent object. Could someone help and advise me on how I can achieve this?

The reason, for doing this, is that I want array of object which will be retrived in a datatable. From my understand, data table accept an array of object for each row. Hence, I want to take the team.name value to the parent object.

Update current vs desired array of object sample code

""

const group = [
  {
    '_id': "61f9b4b59f6601076fff7682",
    'league': "61f1db496de13b0505f08c83",
    'rank': 1,
    'team': {_id: '61f86e813bce5a7bfce4eb6a', name: 'ZizoTeam'},
    'createdAt': "2022-02-01T22:31:17.808Z",
    'updatedAt': "2022-02-01T22:31:17.808Z",
    '__v': 0
  }
]


const group = [
  {
    '_id': "61f9b4b59f6601076fff7682",
    'league': "61f1db496de13b0505f08c83",
    'rank': 1,
    "name": 'ZizoTeam',
    'createdAt': "2022-02-01T22:31:17.808Z",
    'updatedAt': "2022-02-01T22:31:17.808Z",
    '__v': 0
  }
]

""

enter image description here

CodePudding user response:

You can use below aggregation to reshape your document:

db.collection.aggregate([
    {
        $addFields: {
            name: "$team.name"
        }
    },
    {
        $project: { team: 0 }
    }
])

First stage adds new key to existing document and second one is used to remove unnecessary nested object.

Mongo Playground

CodePudding user response:

const group2 = group.map(obj => {
  return {
    ...obj,
    team: obj.team.name,
  };
}
);
console.log(group2);

and to align with your output if you don't need team object and instead only want name

const group2 = group.map(obj => {
  const { team, ...rest } = obj;
  return { ...rest, name: team.name };
});
console.log(group2);
  •  Tags:  
  • Related