Home > Software engineering >  How To Add JSON Value in Existed Nested JSON
How To Add JSON Value in Existed Nested JSON

Time:03-03

its possible for add new value JSON to existed nested JSON ?

My JSON its :

{
"meta": {
    "status": 200,
    "message": "Data retrieval successfully"
},
"data": {
    "id": 1,
    "name": "F4rid arya",
    "created_at": "2022-01-04 02:34:27",
    "updated_at": "2022-01-04 02:34:27",
},
"commision" : 50000
}

I want move the "commision" nested to "data" like this :

{
"meta": {
    "status": 200,
    "message": "Data retrieval successfully"
},
"data": {
    "id": 1,
    "name": "F4rid arya",
    "commision" : 50000
    "created_at": "2022-01-04 02:34:27",
    "updated_at": "2022-01-04 02:34:27",
},
}

This my code for create JSON :

const data = await User.find(id)
                let parsed = ResponseParser.apiItem(data.toJSON())
            
                var jsonCommision = {}
                jsonCommision = {
                    "commision": 15000000
                }
                let assignJson = Object.assign(parsed, jsonCommision)
                return response.status(200).send( assignJson )

CodePudding user response:

You can assign commission property in obj.data by using Object.assign() method and then remove the outer commission property from the object.

Working Demo :

// Original object
const obj = {
  "meta": {
    "status": 200,
    "message": "Data retrieval successfully"
  },
  "data": {
    "id": 1,
    "name": "F4rid arya",
    "created_at": "2022-01-04 02:34:27",
    "updated_at": "2022-01-04 02:34:27",
  },
  "commission" : 50000
};

// Assigning commission property in obj.data object.
Object.assign(obj.data, { "commission": obj.commission });

// Filtered out commission property from an object.
const { commission, ...myObjectRest} = obj;

// Result
console.log(myObjectRest);

CodePudding user response:

try this

const data = await User.find(id);
let parsed = ResponseParser.apiItem(data.toJSON())

parsed.data.commision=parsed.commision;

delete parsed.commision;

return response.status(200).send( parsed )
  • Related