Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
167 views
in Technique[技术] by (71.8m points)

javascript - Convert array of objects into object with property values grouped by key name

How to do it dynamically if we have more objects in input data?

I have dataset array with multiple objects inside it, and objects can be any number. and I have to convert this data into newDataset object with dynamic array inside of it, this array of number dependence on dataset array's objects. I have done this if we have known number of dataset array's objects. for example: see below.

// Input data have dynamic more objects.
var dataset = [
  {
    date: "1 Jan 2020",
    data1: 44,
    data2: 40,
  },
  {
    date: "2 Jan 2020",
    data1: 37,
    data2: 60,
  },
  {
    date: "3 Jan 2020",
    data1: 75,
    data2: 90,
  },
];

var newDataset = {};

// // Output data should be in this form.
// var newDataset = {
//   date: ["1 Jan 2020", "2 Jan 2020", "3 Jan 2020"],
//   data1: [44, 37, 75],
//   data2: [40, 60, 90],
// };


// write your code below

var date = [];
var data1 = [];
var data2 = [];

for (var i = 0; i < dataset.length; i++) {
  date.push(dataset[i].date);
  data1.push(dataset[i].data1);
  data2.push(dataset[i].data2);
}

newDataset.date = date;
newDataset.data1 = data1;
newDataset.data2 = data2;
console.log(newDataset);

//end of your code
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could use a Map object

var dataset = [
  { date: "1 Jan 2020", data1: 44, data2: 40 },
  { date: "2 Jan 2020", data1: 37, data2: 60 },
  { date: "3 Jan 2020", data1: 75, data2: 90 }
];

const myMap = new Map();

dataset.forEach(obj => {
  Object.entries(obj).forEach(([k, v]) => {
    myMap.has(k) ? myMap.get(k).push(v) : myMap.set(k, [v]);
  })
});

console.log(Object.fromEntries(myMap.entries()));
.as-console-wrapper{min-height:100% !important; top: 0; }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...