【问题标题】:Invert key value in js object反转js对象中的键值
【发布时间】:2020-10-27 15:57:27
【问题描述】:

我不知道如何改变:

{"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;
      }, {})
    )

感谢您的帮助!

【问题讨论】:

    标签: javascript


    【解决方案1】:

    Object.entries 将其放入数组,reduce 构建新对象,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】:

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

      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],因此在使用Object.keys 时我不必使用额外的[key] 来获取数组。

      演示:

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

      【讨论】:

        【解决方案3】:

        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;
          }, {})
        )

        【讨论】:

          【解决方案4】:

          试试这个(简单的解决方案),如果这对你有用

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

          【讨论】:

            【解决方案5】:

            您可以对条目进行双重减少。

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

            【讨论】:

              【解决方案6】:

              我没有使用 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);
                    })
                });
              

              【讨论】:

                猜你喜欢
                • 2022-11-18
                • 2021-09-04
                • 1970-01-01
                • 2016-05-12
                • 1970-01-01
                • 2021-12-15
                • 2016-03-18
                • 1970-01-01
                • 2021-11-03
                相关资源
                最近更新 更多