2

I have an array of JavaScript objects, which looks something like this.

[ { name: "A", tp1: 10, tp2: 20, ... tp31: 30 },
  { name: "B", tp1: 11, tp2: 21, ... tp31: 31 },
  { name: "C", tp1: 12, tp2: 22, ... tp31: 32 },
  { name: "D", tp1: 13, tp2: 23, ... tp31: 33 } ]

I want to rearrange the data slightly differently. At the moment, you could say that the "key" (so to speak) is the name. I want the object to be grouped using a different attribute, say tp1, and have the values of each "name" in the object put in as attributes of their own.

My explanation may be terrible, but basically, I want to transform it into the following format:

[ { x: "tp1" , A: 10, B: 11, C: 12, D: 13 },
  { x: "tp2" , A: 20, B: 21, C: 22, D: 23 },
  ...
  { x: "tp31", A: 30, B: 31, C: 32, D: 33 } ]

I genuinely have no idea where to start with this.

Thanks in advance.

Fares K. A.
  • 1,167
  • 5
  • 22
  • 45

1 Answers1

1

let input = [
  { name: "A", tp1: 10, tp2: 20, tp31: 30 },
  { name: "B", tp1: 11, tp2: 21, tp31: 31 },
  { name: "C", tp1: 12, tp2: 22, tp31: 32 },
  { name: "D", tp1: 13, tp2: 23, tp31: 33 }
];
  
let output = Object.keys(input[0])  // get the properties of the first element
              .filter(key => key !== "name")  // "remove" the "name" property
              .map(key => {    // iterate over the remaining keys
                return input.reduce((result, current) => {    // and transform them into the required format
                  result[current.name] = current[key];
                  return result;
                }, { "x": key });    // "start" value for the first .reduce() round
              });

console.log(output);

Methods used:

Object.prototype.keys(): The Object.keys() method returns an array of a given object's own enumerable properties, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).

Array.prototype.filter(): The filter() method creates a new array with all elements that pass the test implemented by the provided function.

Array.prototype.map(): The map() method creates a new array with the results of calling a provided function on every element in this array.

Array.prototype.reduce(): The reduce() method applies a function against an accumulator and each value of the array (from left-to-right) to reduce it to a single value.

Andreas
  • 19,756
  • 7
  • 41
  • 49