1

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}]'
    ]
  }
1
  • 1
    have you tried this instead, objectToReturn = { FieldName: row.FieldName, FieldValues: [...values] }; Commented May 21, 2022 at 15:58

3 Answers 3

1

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

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

1 Comment

Thank you Deepak, the objectToReturn.FieldValues.push(values); is obsolete now, but the spread operator worked
1

you can use spread operator

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax#description

for example:

FieldValues: [...values]

or

objectToReturn.FieldValues.push(...[values]);

1 Comment

Thank you Kavin, I'll read up on the spread operator - this worked wonders :)
0

Hi you can try to do this :

objectToReturn.FieldValues = values

but you need to declare your object as a variable

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.