Home > Software engineering >  Convert JSON to different format using the javascript
Convert JSON to different format using the javascript

Time:04-29

I have the JSON please see below and I need help to convert changing the format mentioned below. I want to move the data to different columns (format mentioned below)

JSON I have

const data =
[
    {
        "2":{
            "value":1.2
        },
        "3":{
            "values":{
                "10.0":1.3
            }
        },
        "4":{
            "value":1.6
        },
    },
    {
        "2":{
            "value":2.2
        },
        "3":{
            "values":{
                "10.0":1.2
            }
        },
        "4":{
            "value":5.6
        },
    },
    
]

I want to change the above to the below format:

Expected format

const data =
[
    {
        col1: "1.2"
        col2: "1.3"
        col3: "1.6"
    },
    {
        col1: "2.2"
        col2: "1.2"
        col3: "5.6"
    },
    
]

CodePudding user response:

I believe this is what you are looking for.

I assumed there are just value or values properties and in values you only need the first one. If my assumption is correct here is your snippet below.

const data = [
  {
    '2': {
      value: 1.2,
    },
    '3': {
      values: {
        '10.0': 1.3,
      },
    },
    '4': {
      value: 1.6,
    },
  },
  {
    '2': {
      value: 2.2,
    },
    '3': {
      values: {
        '10.0': 1.2,
      },
    },
    '4': {
      value: 5.6,
    },
  },
];

const result = data.map((item) => {
  return Object.values(item)
    .reduce((acc, { value = null, values = null }, index) => {
      if (value) return { ...acc, [`col${index   1}`]: String(value) };
      if (values) {
        const [firstItem = null] = Object.values(values);
        if (firstItem) return { ...acc, [`col${index   1}`]: String(firstItem) };
      }
    }, {});
});

console.log(result);

CodePudding user response:

Here's a solution that flattens arbitrarily nested json inputs, assuming only that each column has only one primitive value. It takes advantage of the fact that arrays in js are really just objects with numeric keys.

const data = [
  {
    '2': {
      value: 1.2,
    },
    '3': {
      values: {
        '10.0': 1.3,
      },
    },
    '4': {
      value: 1.6,
    },
  },
  {
    '2': {
      value: 2.2,
    },
    '3': {
      values: {
        '10.0': 1.2,
      },
    },
    '4': {
      value: 5.6,
    },
  },
];

const flattenedValue = value => {
  while (typeof value == 'object' && value != null) 
    for (const v of Object.values(value)) 
      value = v; 
  return value;
};
const result = data.map(row => 
  Object.fromEntries(
    Object.values(row).map(flattenedValue).map((v, i) => [`col${i   1}`, v])
  )
);

console.log(result);

  • Related