简体   繁体   中英

Adding array of objects to object

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}]'
    ]
  }

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

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

Hi you can try to do this :

objectToReturn.FieldValues = values

but you need to declare your object as a variable

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