【问题标题】:How can I reverse an array of object in Javascript?如何在 Javascript 中反转对象数组?
【发布时间】:2022-02-17 23:42:25
【问题描述】:

我有一个这样写的数组:

[
  { TestMetaCoin: 'L', 'Contract: MetaCoin': 'K' },
  { TestMetaCoin: 'L', 'Contract: MetaCoin': 'L' },
  { TestMetaCoin: 'L', 'Contract: MetaCoin': 'K' },
  { TestMetaCoin: 'L', 'Contract: MetaCoin': 'L' }
]

我想得到一个这样写的数组:

[
  { L: 'TestMetaCoin', K: 'Contract: MetaCoin' },
  { L: ['TestMetaCoin','Contract: MetaCoin'] },
  { L: 'TestMetaCoin', K: 'Contract: MetaCoin'  },
  { L: ['TestMetaCoin','Contract: MetaCoin'] }
]

我尝试使用nodejs函数restore()但结果是:

[
  { L: 'TestMetaCoin', K: 'Contract: MetaCoin' },
  { L: 'Contract: MetaCoin' },
  { L: 'TestMetaCoin', K: 'Contract: MetaCoin' },
  { L: 'Contract: MetaCoin' }
]

它完全覆盖了位置 2 和 4 的值,可能是因为它试图创建一个现有的键,因此无法创建它,它通过覆盖存在的值而不是创建具有 2 个值的数组来访问旧的键。 我怎样才能解决这个问题? 这是我使用的代码:

var fristArray= [
  { TestMetaCoin: 'L', 'Contract: MetaCoin': 'K' },
  { TestMetaCoin: 'L', 'Contract: MetaCoin': 'L' },
  { TestMetaCoin: 'L', 'Contract: MetaCoin': 'K' },
  { TestMetaCoin: 'L', 'Contract: MetaCoin': 'L' }
]
var swapped=[]
for(var i=0;i<fristArray.length;i++) {
swapped.push(Object.fromEntries(Object.entries(fristArray[i]).map(([k, v]) => [v, k])))
}
console.log(swapped)

【问题讨论】:

    标签: javascript node.js arrays revert


    【解决方案1】:

    您可以首先使用新键创建目标对象,并为每个空数组作为值。然后填充这些数组。最后,当它们碰巧只有一个元素时,将这些数组中的任何一个替换为单个值。否则将它们保留为数组:

    function swapper(obj) {
        let result = Object.fromEntries(Object.values(obj).map(value => [value, []]));
        for (let [key, value] of Object.entries(obj)) result[value].push(key);
        for (let [key, value] of Object.entries(result)) {
            if (value.length === 1) result[key] = value[0];
        }
        return result;
    }
    
    var firstArray = [{ TestMetaCoin: 'L', 'Contract: MetaCoin': 'K' },{ TestMetaCoin: 'L', 'Contract: MetaCoin': 'L' },{ TestMetaCoin: 'L', 'Contract: MetaCoin': 'K' },{ TestMetaCoin: 'L', 'Contract: MetaCoin': 'L' }];
    var swapped = firstArray.map(swapper);
    console.log(swapped);

    另类

    这里我们先存储单个值,需要的时候再转成数组。

    function swapper(obj) {
        let result = {};
        for (let [key, value] of Object.entries(obj)) {
            result[value] = value in result ? [key].concat(result[value]) : key;
        }
        return result;
    }
    
    var firstArray = [{ TestMetaCoin: 'L', 'Contract: MetaCoin': 'K' },{ TestMetaCoin: 'L', 'Contract: MetaCoin': 'L' },{ TestMetaCoin: 'L', 'Contract: MetaCoin': 'K' },{ TestMetaCoin: 'L', 'Contract: MetaCoin': 'L' }];
    var swapped = firstArray.map(swapper);
    console.log(swapped);

    【讨论】:

      【解决方案2】:

      如果您有兴趣,这里有一个详细的单行解决方案,只使用 ES6 函数。

      var fristArray = [
        { TestMetaCoin: 'L', 'Contract: MetaCoin': 'K' },
        { TestMetaCoin: 'L', 'Contract: MetaCoin': 'L' },
        { TestMetaCoin: 'L', 'Contract: MetaCoin': 'K' },
        { TestMetaCoin: 'L', 'Contract: MetaCoin': 'L' }
      ]
      
      var swapped = fristArray.map(obj => 
        Object.entries(obj).reduce((acc, [k, v]) => ({ ...acc, [v]: acc[v] ? [acc[v], k].flat() : k }), {})
      );
      
      console.log(swapped);

      【讨论】:

      • reducemap 是 ES5,对吧? (+1)
      • @trincot 你是对的,抱歉不够精确,但你明白了:P
      【解决方案3】:

      你可以试试这样的:

      const invertKeyValues = (obj, fn) =>
        Object.keys(obj).reduce((acc, key) => {
          const val = fn ? fn(obj[key]) : obj[key];
          acc[val] = acc[val] || [];
          acc[val].push(key);
          return acc;
        }, {});
      

      【讨论】:

        【解决方案4】:

        const arr = [
          { TestMetaCoin: 'L', 'Contract: MetaCoin': 'K' },
          { TestMetaCoin: 'L', 'Contract: MetaCoin': 'L' },
          { TestMetaCoin: 'L', 'Contract: MetaCoin': 'K' },
          { TestMetaCoin: 'L', 'Contract: MetaCoin': 'L' },
        ];
        const reverseArr = arr.map(obj => {
          const newObj = {};
          Object.keys(obj).forEach(key => {
            const newKey = obj[key];
            if (newObj[newKey]) {
              if (Array.isArray(newObj[newKey])) {
                newObj[newKey].push(key);
              } else {
                newObj[newKey] = [newObj[newKey], key];
              }
            } else {
              newObj[newKey] = key;
            }
          });
          return newObj;
        }
        );
        console.log(reverseArr);

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-09-13
          • 1970-01-01
          • 2021-11-02
          • 2021-12-29
          • 1970-01-01
          • 2012-04-08
          • 2019-04-06
          • 2022-01-01
          相关资源
          最近更新 更多