如何在现有嵌套 JSON 中添加 JSON 值

How To Add JSON Value in Existed Nested JSON

可以向现有的嵌套 JSON 添加新值 JSON 吗?

我的 JSON 它的 :

{
"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
}

我想像这样移动嵌套到“数据”的“佣金”:

{
"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",
},
}

这是我创建 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 )

您可以使用Object.assign()方法在obj.data中分配commission属性,然后从对象中删除外部commission属性 .

工作演示:

// 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);

试试这个

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 )