I am trying to return some data as JSON.
I have an array of values:
[
{ FieldValue: '102969', count: 1 },
{ FieldValue: 'DBFL', count: 26 },
{ FieldValue: 'Daniel', count: 1 },
{ FieldValue: 'KNI', count: 9 },
{ FieldValue: 'ON', count: 895 },
{ FieldValue: 'Ole', count: 4 },
{ FieldValue: 'TNJ', count: 133 }
]
That I am trying to add to an object, in order to get an object with a fieldname, and a values array
const objectToReturn = {
FieldName: row.FieldName,
FieldValues: []
};
objectToReturn.FieldValues.push(values);
returnArr.push(objectToReturn);
console.log(returnArr);
This gives
[
{ FieldName: 'Customer ID', FieldValues: [ [Array] ] },
{ FieldName: 'Order No', FieldValues: [ [Array] ] },
{ FieldName: 'Technician ID', FieldValues: [ [Array] ] }
]
I've tried using JSON.stringify(values) in stead, giving me this return
{
FieldName: 'Technician ID',
FieldValues: [
'[{"FieldValue":"102969","count":1},{"FieldValue":"DBFL","count":26},{"FieldValue":"Daniel","count":1},{"FieldValue":"KNI","count":9},{"FieldValue":"ON","count":895},{"FieldValue":"Ole","count":4},{"FieldValue":"TNJ","count":133}]'
]
}
CodePudding user response:
Hi you can try to do this :
objectToReturn.FieldValues = values
but you need to declare your object as a variable
CodePudding user response:
you have to write it like this:
objectToReturn.FieldValues = values;
CodePudding user response:
You need to write something like this,
const objectToReturn = {
FieldName: row.FieldName,
FieldValues: [...values]
};
objectToReturn.FieldValues.push(values);
returnArr.push(objectToReturn);
console.log(returnArr);
I don't agree with other answers as they will have the object reference problem, I assume you need to have a copy of values array not the array itself