Home > Net >  Array of objects to comma separated array javascript
Array of objects to comma separated array javascript

Time:10-09

I'm trying to convert array of objects to comma separated string array.

Input:

report: [{"name":"abc","age":23,"gender":"male"},
         {"name":"def","age":24,"gender":"female"},
         {"name":"ghi","age":25,"gender":"other"}]

Expected Output:

[["abc",23,"male"],["def",24,"female"],["ghi",25,"other"]]

Code:

resultArray: any = [];

report.forEach(d => {
var energy = Object.values(d).join(",");
this.resultArray.push([energy]);
});

Result: [["abc,23,male"],["def,24,female"],["ghi,25,other"]]

Where am i wrong?

CodePudding user response:

With .join(','), you're turning each object you're iterating over into a single string. If you want 3 separate elements, don't join.

const report = [{"name":"abc","age":23,"gender":"male"},
         {"name":"def","age":24,"gender":"female"},
         {"name":"ghi","age":25,"gender":"other"}]

const resultArray = [];

report.forEach(d => {
  var energy = Object.values(d);
  resultArray.push(energy);
});
console.log(resultArray);

Or, better:

const report = [{"name":"abc","age":23,"gender":"male"},
         {"name":"def","age":24,"gender":"female"},
         {"name":"ghi","age":25,"gender":"other"}]

const resultArray = report.map(Object.values);
console.log(resultArray);

CodePudding user response:

join(',') will join array separated by , and you are assigning it in array as:

this.resultArray.push([energy]);

All you have to do is:

var energy = Object.values(d);  // get all the values of an object
this.resultArray.push(energy);  // Pust energy values in resultArray

const report = [
    { name: 'abc', age: 23, gender: 'male' },
    { name: 'def', age: 24, gender: 'female' },
    { name: 'ghi', age: 25, gender: 'other' },
];

const resultArray = [];

report.forEach((d) => {
    var energy = Object.values(d);
    resultArray.push(energy);
});

console.log(resultArray);

  • Related