简体   繁体   中英

JS pivot data from "wide" to "long"

I have tabular data that looks like this:

在此处输入图片说明

And ultimately what I want to achieve is this:

在此处输入图片说明

The data can be parsed and managed in any way, but it begins it's lifecycle in the tabular format as shown in the first picture.

Edited based on OP's comment.

Let's say input JSON looks like this:

[
...
{
  "record": 1,
  "identity": "student",
  "second_identity": "visitor"
},
{
  "record": 2,
  "identity": "student",
  "second_identity": "resident"
}
...

]

I would convert it to this format:

[
...
{
  "record": 1,
  "identity_long": "student"
},
{
  "record": 1,
  "identity_long": "visitor"
},
{
  "record": 2,
  "identity_long": "student",
},
{
  "record": 2,
  "identity_long": "resident"
}
...

]

Here's the code:

function processData(input) {
  const output = [];
  for (let i = 0; i < input.length; i++) {
    const record = input[i];

    // Add "identity"
    output.push({ record: record.record, identity_long: record.identity });

    // Add "second_identity"
    output.push({ record: record.record, identity_long: record.second_identity });
  }

  return output;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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