提问人:Shan 提问时间:4/29/2023 最后编辑:Shan 更新时间:4/30/2023 访问量:90
如何使用嵌套对象、数组进行动态执行
Dynamic how to execute using nested objects, arrays
问:
按预期工作。
我使用这个JSON主体将其插入到SQL表中传递给JavaScript。
输入
data :
[{
"name": "John",
"detail" : "contact",
"type" : "phone",
"value" : "987-654-3210"
},
{ "name": "John",
"detail" : "contact",
"type" : "email",
"value" : "[email protected]"
},
{ "name": "John",
"detail" : "address",
"type" : "city",
"value" : "Berlin"
},
{ "name": "John",
"detail" : "address",
"type" : "country",
"value" : "Germany"
}]
Javascript 进程
var data;
var rawdata = JSON.parse(JSON.stringify(data));
var query= ""
arrayLength = rawdata.length;
for (var i = 0; i < arrayLength; i++) {
query +=` begin
insert into [dbname].[dbo].[table] (name,detail,type,value)
values('` + rawdata[i].name+ `','` + rawdata[i].detail + `','` + rawdata[i].type+ `','` +
'` + rawdata[i].value + `')
end
}
return query;
SQL 表输出
| name | detail |type |value |
| -------- | -------- |---------|----------------|
| John | contact |phone |987-654-3210 |
| John | contact |email |[email protected] |
| John | address |city |Berlin |
| John | address |country |Germany |
下面我有这个JSON的主体。 如何传递给JavaScript函数以插入SQL表?
输入
{
"data": [{
"name": "John",
"contact": {
"phone": "987-654-3210",
"email": "[email protected]"
},
"address": {
"city": "Berlin",
"country": "Germany"
}
}]
}
SQL 表输出
| name | detail |type |value |
| -------- | -------- |---------|----------------|
| John | contact |phone |987-654-3210 |
| John | contact |email |[email protected] |
| John | address |city |Berlin |
| John | address |country |Germany |
如何创建JavaScript函数?对此有什么建议吗?
答:
0赞
protob
4/30/2023
#1
您可以定义 helper 函数 ,该函数用于从传递的参数 : 及其值条目(例如 )创建 SQL 字符串。buildQuery
map
name
rootKey
["phone", "987-654-3210"]
buildQueries
函数解构要传递给 的参数数据,并用于从对象中提取对数组。buildQuery
Object.entries()
[key, value]
const data = {
"data": [{
"name": "John",
"contact": {
"phone": "987-654-3210",
"email": "[email protected]"
},
"address": {
"city": "Berlin",
"country": "Germany"
}
}]
};
const buildQuery = (name, rootKey, entries) =>
entries.map(([key, value]) => `begin insert into [dbname].[dbo].[table] (name, rootKey, type, value) values('${name}', '${rootKey}', '${key}', '${value}') end;`);
const buildQueries = ({ data: [{ name, contact, address }] }) => [
...buildQuery(name, 'contact', Object.entries(contact)),
...buildQuery(name, 'address', Object.entries(address))
].join('\n');
const query = buildQueries(data);
console.log(query);
上一个:映射对象的嵌套数组
评论