0

From the object 1, I am trying to form another object 2. I have written this below piece of code but I dono is this the right approach to achieve object 2.

var arr = [];
    object1.filter(function(value) {
                                return value.hasOwnProperty("This Year"); // Get only elements, which have such a key
                                    }).map(function(value) {
                                arr.push({value:value["This Year"]}); // Extract the values only
                                    });

Object 1

var obj=[
  {
    "sno": 1,
    "Last Year": 10000
  },
  {
    "sno": 2,
    "Last Year": 11500
  },
  {
    "sno": 3,
    "Last Year": 12500
  },
  {
    "sno": 4,
    "This Year": 25400
  },
  {
    "sno": 5,
    "Last Year": 15000
  },
  {
    "sno": 6,
    "This Year": 29800
  }
]

Object 2 - Desired Result

var dataset = [
        {
            "seriesname": "Last Year",
            "data": [
                {
                    "value": "10000"
                },
                {
                    "value": "11500"
                },
                {
                    "value": "12500"
                },
                {
                    "value": "15000"
                }
            ]
        },
        {
            "seriesname": "This Year",
            "data": [
                {
                    "value": "25400"
                },
                {
                    "value": "29800"
                }
            ]
        }
    ]

If anyone can help me with better approach. In my code I am hard coding the key name of object 1. Is it possible in any other way?

3 Answers 3

2
var obj1 = [
  {
    "sno": 1,
    "Last Year": 10000
  },
  {
    "sno": 2,
    "Last Year": 11500
  },
  {
    "sno": 3,
    "Last Year": 12500
  },
  {
    "sno": 4,
    "This Year": 25400
  },
  {
    "sno": 5,
    "Last Year": 15000
  },
  {
    "sno": 6,
    "This Year": 29800
  }
];

var dataset = [];

["This Year", "Last Year"].forEach((series) => {
    dataset.push({
        seriesname: series,
        data: obj1.filter((el) => {
                return el[series];
            }).map((el) => {
                return {
                    value: el[series]
                }
            })
        });
});

console.log(JSON.stringify(dataset, null, 2));
Sign up to request clarification or add additional context in comments.

2 Comments

A good answer should include an explanation of how it answers the question, e.g. why you think this is "better" than the OP.
Looks like I misunderstood the question.
1

To avoid hard coding the year entries, you could use RegExp to look for a key containing the year word.

var arr = [{sno:1,"Last Year":1e4},{sno:2,"Last Year":11500},{sno:3,"Last Year":12500},{sno:4,"This Year":25400},{sno:5,"Last Year":15e3},{sno:6,"This Year":29800}],
    res = [...new Set(arr.map(v => Object.keys(v).find(z => /year/i.test(z))))]
          .map(c => ({seriesname: c, data: arr.filter(x => x[c]).map(a => ({value: a[c]}))}));
  
console.log(res);

Comments

0

You can extract the keys by getting the unique key names from objects in the input array that aren't sno, then use a reducer to change the data form.

var obj = [
  {
    "sno": 1,
    "Last Year": 10000
  },
  {
    "sno": 2,
    "Last Year": 11500
  },
  {
    "sno": 3,
    "Last Year": 12500
  },
  {
    "sno": 4,
    "This Year": 25400
  },
  {
    "sno": 5,
    "Last Year": 15000
  },
  {
    "sno": 6,
    "This Year": 29800
  }
]

const getSeries = obj => {
    const emptyResult = getSeriesNames(obj).map(seriesName => ({
      seriesName,
      data: []
    }));
    
    return obj.reduce((result, item) => {
        const series = result.filter(series => series.seriesName in item)[0]
        series.data.push({ value: item[series.seriesName] });
        return result;
    }, emptyResult);
}

const getSeriesNames = obj => obj.reduce((names, item) => {
    Object.keys(item)
    .filter(key => key !== 'sno')
    .forEach(key => {
        if (!names.includes(key)) {
            names.push(key);
        }
    });
    return names;
}, []); 

console.log(getSeries(obj));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.