0

I have data in json format and I would like to pivot on the nym dimension. the json data are in the following format:

data=[{
    l: 'es',
    maxversion: '20210620',
    nym: 'http://kaiko.getalp.org/dbnary#antonym',
    count: '2827',
  },
  {
    l: 'es',
    maxversion: '20210620',
    nym: 'http://kaiko.getalp.org/dbnary#approximateSynonym',
    count: '0',
  },
  {
    l: 'es',
    maxversion: '20210620',
    nym: 'http://kaiko.getalp.org/dbnary#holonym',
    count: '0',
  },
{
    l: 'es',
    maxversion: '20210620',
    nym: 'http://kaiko.getalp.org/dbnary#hypernym',
    count: '1589',
  },
  .
  .
  .

  },] 


I would like to have this format after pivot, to be able to use them in a graphic library:

[{
    l: 'es',
    maxversion: '20210620',
    antonym:'2827' ,
    approximateSynonym: '0',
    holonym:'0',
    hypernym:'1589', 
    hyponym:913,
    meronym:'0',
    synonym:'25821',
    troponym: '0'
  },
 ] 

2
  • 1
    Hi Amnay, SO aren't a coding workforce. We're here for help, but, can you try it and post some of your tests? Commented Jun 26, 2021 at 22:08
  • hi Sakura, I have just published my results in response Commented Jun 30, 2021 at 13:07

2 Answers 2

1

You can use Array.prototype.reduce if the other properties (l, maxversion) are the same for every entry.

function pivot(data){
  return data.reduce((accumulator, {nym, count, ...rest}) => ({
    ...accumulator,
    ...rest,
    [nym.split('#')[1]]: count
  }), {});
}

Otherwise you have to group them first by some key.

function groupBy(data, keyname){
    let result = {};
    data.forEach((item) => {
        const key = item[keyname];
        result[key] = [...(result[key] || []), item];
    })
    return Object.values(result);
}

Example usage grouped by l:

const result = groupBy(data, 'l').map(pivot);
Sign up to request clarification or add additional context in comments.

Comments

0

Since my data is not the same I used the groupBy function const result = groupBy(data, 'l').map(pivot); and it works perfectly for me here is what I get:

[
  {
    l: 'es',
    maxversion: '20210620',
    antonym: '2827',
    approximateSynonym: '0',
    holonym: '0',
    hypernym: '1589',
    hyponym: '913',
    meronym: '0',
    synonym: '25821',
    troponym: '0'
  },
  {
    l: 'bg',
    maxversion: '20210620',
    antonym: '40',
    approximateSynonym: '0',
    holonym: '0',
    hypernym: '0',
    hyponym: '0',
    meronym: '0',
    synonym: '17399',
    troponym: '0'
  },

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.