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



我有一个这样的对象-

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

我想要一个对象,其条目映射如下-车辆h1到车轮1车h2到车轮2汽车h3到车轮3等等生成的对象应该是这样的-

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

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

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

但还有什么更好的方法呢?条目数可以是任何数字"n"。

如何通过javascript实现这一点?

  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; }

您可以这样做:

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);

相关内容

  • 没有找到相关文章

最新更新