Skip to content
Advertisement

How To Add JSON Value in Existed Nested JSON

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 )

Advertisement

Answer

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);
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement