Home > Software design >  How to break a single JSON object in multiple objects
How to break a single JSON object in multiple objects

Time:03-01

I am new to this please excuse me if I make any mistake.

I am reading a single row of data from database , the data which I receive is JSON object and looks like this:

var details = {jan: '2591.00', feb: '4898.00', mar: '26290.00', apr: '22719.00', may: '26528.00',start: '2020', end: '2022', v1: '34', v2: '22'};

Now I want to alter/modify this JSON object so it looks like this:

var details = [
{jan: '2591.00',start: '2020', end: '2022', v1: '34', v2: '22'},
{feb: '4898.00',start: '2020', end: '2022', v1: '34', v2: '22'},
{mar: '26290.00',start: '2020', end: '2022', v1: '34', v2: '22'},
{apr: '22719.00',start: '2020', end: '2022', v1: '34', v2: '22'},
{may: '26528.00',start: '2020', end: '2022', v1: '34', v2: '22'}

]

MY Approach: I have been trying to achieve this by using :

result = Object
        .keys(details)
        .map(k => ({ [k]: details[k] }));

However, it will break at each key-value pair.

var details = {jan: '2591.00', feb: '4898.00', mar: '26290.00', apr: '22719.00', may: '26528.00',start: '2020', end: '2022', v1: '34', v2: '22'};



var details = [
{jan: '2591.00',start: '2020', end: '2022', v1: '34', v2: '22'},
{feb: '4898.00',start: '2020', end: '2022', v1: '34', v2: '22'},
{mar: '26290.00',start: '2020', end: '2022', v1: '34', v2: '22'},
{apr: '22719.00',start: '2020', end: '2022', v1: '34', v2: '22'},
{may: '26528.00',start: '2020', end: '2022', v1: '34', v2: '22'}

]

CodePudding user response:

let details = {
  jan: '2591.00',
  feb: '4898.00',
  mar: '26290.00',
  apr: '22719.00',
  may: '26528.00',
  start: '2020',
  end: '2022',
  v1: '34',
  v2: '22'
};
let months = ['jan', 'feb', 'mar', 'apr', 'may'];

let detailsByMonth = months.map(month => ({
  [month]: details[month],
  start: details.start,
  end: details.end,
  v1: details.v1,
  v2: details.v2
}));

console.log(detailsByMonth);

CodePudding user response:

Here is a one liner. First I filter the keys of the object based on what you don't want inside the array (opposite can be done as well). Then I map them into objects of required type.

const mappedDetails = Object.keys(details)
    .filter((i) => !["v1", "v2", "start", "end"].includes(i))
        .map((j) => ({
            [j]: details[j], 
            start: details.start, 
            end: details.end, 
            v1: details.v1, 
            v2: details.v2
        })
    );

CodePudding user response:

try this

var arrContinue = ["start", "end", "v1", "v2"];
const newDetails = Object.keys(details)
  .filter(k => (arrContinue.indexOf(k) == -1))
  .map(k => ({
    [k]: details[k],
    start: details.start,
    end: details.end,
    v1: details.v1,
    v2: details.v2,
  }));
  • Related