如何根据另一个对象的键顺序的优先级创建一个对象?

How does one create an object based on the precedence of another object's key order?

我有一个这样的对象-

const obj = {
    'veh1': 'Car',
    'veh2': 'Bicycle',
    'veh3': 'Truck',
    'wheels1': '4',
    'wheels2': '2',
    'wheels3': '8'
}

我想要一个对象,它的条目映射如下- veh1 到 wheels1veh2 到 wheels2veh3 到 wheels3 等等 结果对象应该是这样的-

const result = {
    'Car': '4',
    'Bicycle': '2',
    'Truck': '8'
}

我知道,我们可以这样直接做-

{
   [obj.veh1]: obj.wheels1,
   [obj.veh2]: obj.wheels2,
   [obj.veh3]: obj.wheels3
}

但是更好的方法是什么?条目数可以是任意数字'n'.

如何通过 javascript 实现此目标?

你可以这样做:

const vehicles = {};
const wheels = {};
const result = {};

for (key in obj) {
  if (key.startsWith("veh")) {
    const id = key.replace("veh", "");
    vehicles[id] = obj[key];
    if (wheels.hasOwnProperty(id)) {
      result[vehicles[id]] = wheels[id];
    }
  } else if (key.startsWith("wheels")) {
    const id = key.replace("wheels", "");
    wheels[id] = obj[key];
    if (vehicles.hasOwnProperty(id)) {
      result[vehicles[id]] = wheels[id];
    }
  }
}
const obj = {
  'veh1': 'Car',
  'veh2': 'Bicycle',
  'veh3': 'Truck',
  'wheels1': '4',
  'wheels2': '2',
  'wheels3': '8'
}

let res = {};
let keys = Object.keys(obj);
let i;
for(i = 0; i < keys.length; i ++) {
  if(keys[i].slice(0, 3) === 'veh') {
    res[obj[keys[i]]] = obj[`wheels${keys[i].slice(3)}`];
  }
}

console.log(res);
  1. 从提供的对象创建条目(键值对)。
  2. 按每个条目的关键字对条目进行排序。
  3. 最后从上半部分(或左半部分)和下半部分(或右半部分)之前排序的条目创建一个新对象。

function localeCompare(a, b) {
  return (a.localeCompare && b.localeCompare
    && a.localeCompare(b))
    || (((a < b) && -1) || ((a > b) && 1) || 0);
}

function compareEntriesByKey(entryA, entryB) {
  return localeCompare(entryA[0], entryB[0]);
}

function createKeyValuePairFromSortedEntryHalfs(obj, $, idx, entries) {
  if (((idx + 1) % 2) === 0) {
 
    const keyIdx = ((idx - 1) / 2);
    const valueIdx = (keyIdx + Math.floor(entries.length / 2));

    const key = entries[keyIdx][1];
    const value = entries[valueIdx][1];

    obj[key] = value;
  }
  return obj;
}


const obj = {
  'wheels3': '8',
  'veh3': 'Truck',
  'wheels1': '4',
  'veh1': 'Car',
  'wheels2': '2',
  'veh2': 'Bicycle',
}
const result = Object
  // (1) create entries (key value pairs) from the provided object.
  .entries(obj)
  // (2) sort the entries by each of an entry's key.
  .sort(compareEntriesByKey)
  // (3) finally create a new objects from the upper (or left) as
  //     well the lower (or right) half of the before sorted entries.
  .reduce(createKeyValuePairFromSortedEntryHalfs, {});

console.log('result :', result);

console.log('obj', obj);
console.log(
  'Object.entries(obj).sort(compareEntriesByKey)',
  Object.entries(obj).sort(compareEntriesByKey)
);

console.log(
  'proof of being a generic approach...', `
  Object.entries({
    'foo-biz': 'biz',
    'x': 111,
    'foo-baz': 'baz',
    'y': 222,
    'foo-bar': 'bar',
    'z': 333,
  }).sort(
    compareEntriesByKey
  ).reduce(
    createKeyValuePairFromSortedEntryHalfs,
    {}
  ) =>`, Object.entries({
    'foo-biz': 'biz',
    'x': 111,
    'foo-baz': 'baz',
    'y': 222,
    'foo-bar': 'bar',
    'z': 333,
  }).sort(
    compareEntriesByKey
  ).reduce(
    createKeyValuePairFromSortedEntryHalfs,
    {}
  )
);
.as-console-wrapper { min-height: 100%!important; top: 0; }