简体   繁体   English

如何将 JSON 中的 SQL 主键转换为 javascript ZA8CFDE6331BD59EB266AC96F89111 和其他数据作为它的值

[英]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.

相关问题 使用键和值将JSON数据转换为javascript对象 - Convert JSON data into javascript object with key and value 如何在 css 中使用 javaScript object 键的值? - How can I use a javaScript object key's value in css? 如何通过分组密钥将 json 转换为 javascript object - How to convert json into a javascript object, with grouping a key 我如何将这个AJAX json结果(具有键/值属性)转换为javascript数组 - How can i convert this AJAX json result (which has a key/value property) into a javascript array 如何在 Javascript json 变量中添加新键及其值 - how can add new key and it's value in Javascript json variable 用 JavaScript 将对象值替换为具有相同键的其他对象的值 - Replace object value with other object's value of the same key with JavaScript 在javascript中将Json对象转换为键值对的Json数组 - Convert Json object to Json array of key-value pair in javascript 在JavaScript中,如何返回一个布尔值,指示一个键是否存在于JSON对象中? - In JavaScript, how can I return a boolean value indicating whether a key is present in a JSON object? 如何使用Javascript检索Json中的键/值对象? - How to retrieve the key/value object in Json with Javascript? 如何使用javascript在json中搜索指定的结果[键+值]? - How can i search for an specified result[key + value] in a json with javascript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM