javascript - Object transformation assistance
问题描述
I have a list of single key value pairs, where the key is a 2 part string that describes where the value should be plotted on a table. This is the first time I've asked a questions on SO so please go easy on me.
let tiles = [
{ 'A~baz': 'x' },
{ 'A~buzz': 'o' },
{ 'A~fam': '' },
{ 'B~baz': 'x' },
{ 'B~buzz': '' },
{ 'B~fam': '' },
{ 'C~baz': 'x' },
{ 'C~buzz': 'x' },
{ 'C~fam': 'x' }
]
I want to convert it into the below format.
[
{ _id: 'A', baz: 'x', buzz: 'o', fam: '' },
{ _id: 'B', baz: 'x', buzz: '', fam: '' },
{ _id: 'C', baz: 'x', buzz: 'x', fam: 'x' }
]
Note I will need to perform this operation on hundreds of thousands of key value pairs.
What I have done so far, this works, but I was hoping there could be places I can make improvements.
let tiles = [
{ 'C~fam': "x" },
{ 'B~buzz': "" },
{ 'B~fam': "" },
{ 'A~fam': "" },
{ 'A~buzz': "o" },
{ 'B~baz': "x" },
{ 'A~baz': "x" },
{ 'C~baz': "x" },
{ 'C~buzz': "x" },
];
// I thought it would help to sort the array
tiles.sort((a, b) => Object.keys(a)[0].localeCompare(Object.keys(b)[0]));
let obj = {};
tiles.forEach((kvp) => { //kvp = key value pair
let [row,col] = Object.keys(kvp)[0].split('~') //destruct by '~'
let val = Object.values(kvp)[0];
obj[row] = obj[row] ?? {}
obj[row][col] = val;
})
let keys = Object.keys(obj);
let values = Object.values(obj)
let output = [];
for (let i = 0, len = keys.length; i < len; i++) {
output.push(Object.assign({_id : `${keys[i]}`}, values[i]));
}
解决方案
您通过对数组进行排序来谴责算法的复杂性为 O(nlog(n))。您可以解决此问题而无需对其进行排序。由于我们必须遍历所有数组,因此可能的最佳复杂度是 O(n)。假设输入格式始终保持不变,试试这个:
function changeFormat (arr){
const hash = {}
arr.forEach(element => {
const key = Object.keys(element)[0];
const _id = key[0];
if (hash[_id] === undefined)
hash[_id] ={_id, baz:'', buzz:'', fam:''};
const type = key.slice(2);
hash[_id][type] = element[key];
});
return Object.values(hash);
}
推荐阅读
- python - 从图像中提取特定文本
- python-3.x - Tkinter 滚动条不会控制入口小部件
- javascript - 在会话存储中使用数组保存表单数据
- c++ - 为什么在使用花括号初始化结构时出现错误?
- amazon-web-services - AWS kubernetes 完成工作后调用 lambda 函数
- swift - 在 SwiftUI 中定位另一个视图的位置
- amazon-web-services - Cloudformation:如何通过 cloudformation 脚本将字符串传递给 UserData?
- c# - Visual FoxPro 运行带参数的 C# 程序
- javascript - process.env 在我 console.log 时工作,但当我插入密钥时将无法工作
- spring-boot - 使用java rest api逐块上传大文件