Flip key value pair on 1 lvl depth

a 夏天 提交于 2021-01-04 09:22:03

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!