首页 > 解决方案 > 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]));
}

标签: javascriptarraysexport-to-csv

解决方案


您通过对数组进行排序来谴责算法的复杂性为 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);
}


推荐阅读