Home > Blockchain >  How can I reverse an array of object in Javascript?
How can I reverse an array of object in Javascript?

Time:02-18

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:

[
  { 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. 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)

CodePudding user response:

You can first create the target object with the new keys and for each an empty array as value. Then populate those arrays. Finally replace any of those arrays by a single value when they happen to only have one element. Else leave them as 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);

CodePudding user response:

Here's an elaborated one-liner solution using nothing but ES6 functions if you're interested.

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

CodePudding user response:

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

CodePudding user response:

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

  • Related