问题
I have object:
const pairs = {
A: { D: [1, 2, 3] },
B: { D: [3, 2, 1] },
C: {
D: [4, 3, 2, 1],
B: [0, 1, 2, 3]
}
};
How can I get it fliped?
const fliped = {
D: { A: [1, 2, 3], B: [3, 2, 1], C: [4, 3, 2, 1] },
B: { C: [0, 1, 2, 3] }
};
ES6 solution will be great
I tried something like, but find that im not very good with reduce method and start thinkind about ugly imperative solution:
Object.entries(pairs).reduce(
(acc, [key1, value]) =>
Object.keys(value).reduce(
(acc, key2) => ({
...acc,
[key2]: { [key1]: value[key2] }
}),
acc
),
{}
);
回答1:
You could take a nested approach by reducing the entries of the objects.
const
pairs = { A: { D: [1, 2, 3] }, B: { D: [3, 2, 1] }, C: { D: [4, 3, 2, 1], B: [0, 1, 2, 3] } },
result = Object
.entries(pairs)
.reduce((r, [right, object]) => Object
.entries(object)
.reduce((r, [left, value]) => {
r[left] = r[left] || {};
r[left][right] = value;
return r;
}, r), {});
console.log(result);
Another approach is to use a recursive function by creating the properties after collecting all keys.
const
reverse = (source, target = {}, keys = []) => {
if (source && typeof source === 'object' && !Array.isArray(source)) {
Object.entries(source).forEach(([k, v]) => reverse(v, target, [k, ...keys]));
} else {
var last = keys.pop();
keys.reduce((o, k) => o[k] = o[k] || {}, target)[last] = source;
}
return target;
},
pairs = { A: { D: [1, 2, 3] }, B: { D: [3, 2, 1] }, C: { D: [4, 3, 2, 1], B: [0, 1, 2, 3] } },
result = reverse(pairs);
console.log(result);
来源:https://stackoverflow.com/questions/59706836/flip-key-value-pair-on-1-lvl-depth