skip to Main Content

There is an json array from mongodb database as shown below.

[
    {
        "_id": {
            "fx_capacity_category": "100~300"
        },
        "fx_capacity": 314898.0758
    },
    {
        "_id": {
            "fx_capacity_category": "300~500"
        },
        "fx_capacity": 145033.1
    },
    ...
] 

This dataset needed to be transformed to be flat while removing the "_id"

[
    {
        "fx_capacity_category": "300~500"
        "fx_capacity": 145033.1
    },
    ...
]

I know the way of doing this by iterating the array item, and finding the item with ‘_id’ and associated leaf key and transform. But that is not a smart way, wondering any better way, for example using lodash.

2

Answers


  1. You could remove _id and build a new object with rest and destructured object.

    const
        data = [{ _id: { fx_capacity_category: "100~300" }, fx_capacity: 314898.0758 }, { _id: { fx_capacity_category: "300~500" }, fx_capacity: 145033.1 }],
        result = data.map(({ _id, ...rest }) => ({ ...rest, ..._id }));
    
    console.log(result);
    Login or Signup to reply.
  2. You could use flatMap

    data.flatMap((i) => {
      delete i._id; 
      return i; 
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search