简体   繁体   中英

Array of objects to comma separated array javascript

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?

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);

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM