简体   繁体   English

如何在 Javascript 中反转 object 的数组?

[英]How can I reverse an array of object in Javascript?

I have an array written in this way:我有一个这样写的数组:

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

And I want to obtain an array writtenin this way:我想获得一个这样写的数组:

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

I tryed to use the nodejs function restore() but the result is:我尝试使用 nodejs function restore()但结果是:

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

It completely overwrites the value in position 2 and 4, probably because it tries to create an existing key and therefore not being able to create it, accesses the old one by overwriting the value exists instead of creating an array with 2 values.它完全覆盖了 position 2 和 4 中的值,可能是因为它试图创建一个现有的密钥,因此无法创建它,通过覆盖存在的值而不是创建具有 2 个值的数组来访问旧密钥。 How can I get around this problem?我怎样才能解决这个问题? This is the code that I use:这是我使用的代码:

 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)

You can first create the target object with the new keys and for each an empty array as value.您可以先使用新键创建目标 object,并为每个键创建一个空数组作为值。 Then populate those arrays. Finally replace any of those arrays by a single value when they happen to only have one element.然后填充那些 arrays。最后,当它们恰好只有一个元素时,用单个值替换任何 arrays。 Else leave them as arrays:否则将它们保留为 arrays:

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

Alternative选择

Here we store a single value first, and then turn it into an array when needed.这里我们先存储一个单一的值,然后在需要的时候把它变成一个数组。

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

Here's an elaborated one-liner solution using nothing but ES6 functions if you're interested.如果您有兴趣,这里有一个精心设计的单行解决方案,只使用 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);

You can try something like this:你可以尝试这样的事情:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM