反转js对象中的键值

时间:2020-10-27 15:57:27

标签: javascript

我不知道该如何改变:

{"first":["de"], "second":["ab","de"], "third":["de"]}

收件人:

{"de":["first", "second", "third"], "ab":["second"]}

我想将唯一值与包含键的列表相关联。我尝试过的方法(但我想我还很远):

 const data = {
      "first":["de"],
      "second":["ab","de"],
      "third":["de"]
    }
    
    console.log(
      Object
      .keys(data).reduce(function(obj, key) {
        obj[data[key]] = key;
        return obj;
      }, {})
    )

感谢您的帮助!

6 个答案:

答案 0 :(得分:2)

您必须循环数组,并为数组中的每个项目检查累加器中是否存在该值的数组,然后再添加它:

let result = Object.entries(data).reduce((acc, [key, arr]) => { // for each key-array of the original object
  arr.forEach(value => {                                        // for each value in the array
    acc[value] = acc[value] || [];                              // create an array in the output object if it doesn't already exist
    acc[value].push(key);                                       // push the key to it
  });

  return acc;
}, {});

我还使用了Object.entries,每个条目都被描述为[key, arr],因此在使用[key]时不必使用多余的Object.keys来获取数组。

演示:

let data = {"first":["de"], "second":["ab","de"], "third":["de"]};

let result = Object.entries(data).reduce((acc, [key, arr]) => {
  arr.forEach(value => {
    acc[value] = acc[value] || [];
    acc[value].push(key);
  });

  return acc;
}, {});

console.log(result);

答案 1 :(得分:2)

Object.entries将其放入数组中,简化以构建新对象,并让forEach遍历数组

const o = {"first":["de"], "second":["ab","de"], "third":["de"]}

const result = Object.entries(o).reduce((obj, [key, arr])=>{
  arr.forEach(lng => {
    obj[lng] = obj[lng] || [];
    obj[lng].push(key);
  })
  return obj
}, {});

console.log(result);

答案 2 :(得分:1)

reduce回调中,data[key]是一个字符串值数组。因此,需要循环data[key]个数组值并为每个数组项分配值。

const data = {
  "first":["de"],
  "second":["ab","de"],
  "third":["de"]
}

console.log(
  Object.keys(data).reduce(function(obj, key) {
    data[key].forEach((val) => {
      obj[val] ? obj[val].push(key) : obj[val] = [ key ];
    });
    return obj;
  }, {})
)

答案 3 :(得分:0)

尝试此方法(天真解决方案),如果它对您有用

const data = { first: ["de"], second: ["ab", "de"], third: ["de"] };

let dataMap = new Map();
Object.keys(data).forEach((key) => {
  data[key].forEach((val) => {
    if (dataMap.has(val)) {
      dataMap.set(val, [...dataMap.get(val), key]);
    } else {
      dataMap.set(val, [key]);
    }
  });
});

let nData = [];
dataMap.forEach((value, key) => {
  nData.push({
    [key]: value
  });
});

console.log(nData);

答案 4 :(得分:0)

您可以对条目进行两次缩减。

const
    data = { first: ["de"], second: ["ab", "de"], third: ["de"] },
    result = Object
        .entries(data)
        .reduce((o, [value, keys]) => keys.reduce((q, key) => {
            (q[key] ??= []).push(value);
            return q;
        }, o), {});

console.log(result);

答案 5 :(得分:0)

我没有使用reduce,但这是解决问题的“蛮力”,

res = {};

Object.keys(data).forEach(key => {
      data[key].forEach(el => {
          if (! res[el])
            res[el] = [];
        
         if (! res[el].includes(key))
            res[el].push(key);
      })
  });