I'm trying to create an JSON from another JSON using Javascript.
Here is my code.
var data = [{
"Id": "123",
"Name": "Abc",
"Amount": 110000
},
{
"Id": "567",
"Name": "DEF",
"Amount": 98000
},
{
"Id": "345",
"Name": "XYZ",
"Amount": 145000
}
];
finalArray(data);
function finalArray(data) {
var nArray = [];
var subArray = new Object();
subArray.total = 0;
subArray.records = {};
subArray.size = 0;
data.forEach(item => {
subArray.total += item.Amount;
subArray.records += item;
subArray.size += 1;
});
nArray.push(subArray);
console.log(nArray);
};
Here In the final object, In records I'm getting the below output.
records: "[object Object][object Object][object Object][object Object]"
expected output is
records: "[object Object][object Object][object Object]"
where as in my actual data, I've 3 records in the input.
Please let me know where I'm going wrong.
Thanks
[object Object]s is because you initializerecordswithsubArray.records = {};, i.e. an object. Then you are trying to "add" another object withsubArray.records += item;. This will result in[object Object][object Object]since you are "concatenating" two objects. It goes without saying that concatenating objects as string is wrong.