[英]How can I convert an SQL primary key in JSON to a javascript object key with the other data as it's value
Whenever I read all my data from a database table and receive it as JSON from my API, I get my data like this ( unique_name
being the primary key in this example):每当我从数据库表中读取所有数据并从我的 API 中将其作为 JSON 接收时,我都会得到这样的数据(在此示例中,
unique_name
是主键):
[{"unique_name":"alice", "age":18, "city":"kansas"},{"unique_name":"bob", "age":20, "city":"chicago"}]
In my javascript application, however, I need my data to be formatted like so:然而,在我的 javascript 应用程序中,我需要像这样格式化我的数据:
const myData = {alice: {age:18, city:"kansas"}, bob: {age:20, city:"chicago"}}
I guess this could be done with object mapping of some sort, but I'm afraid this would be too slow with a lot of entries.我想这可以通过某种类型的 object 映射来完成,但我担心这对于很多条目来说太慢了。 Is there any clean way to do this?
有什么干净的方法可以做到这一点吗?
There is no real problem to map a lot of entries. map 很多条目没有真正的问题。 If you want more performences you should do it server side (eg: on a nodejs server)
如果您想要更多性能,您应该在服务器端进行(例如:在 nodejs 服务器上)
You can simply use a .forEach()
您可以简单地使用
.forEach()
Exemple (not complete so you just get the idea)示例(不完整,所以你只是明白了)
const myData = {};
mySQL.forEach(entry => myData[entry.unique_key] = entry)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.