1

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?

0

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.