Reputation: 139
I have a JSON object where I need to append the fields bioDescription
and bioPicUrl
to the object before I JSON.stringify()
the data. I can add the fields and it outputs the to the screen as a JSON object as seen in output below.
OUTPUT
[4/10/2020 3:59:23 PM] OUTPUT
[4/10/2020 3:59:23 PM] _id: 5e907943a9a0e12b90b178c9,
[4/10/2020 3:59:23 PM] title: 'test',
[4/10/2020 3:59:23 PM] startingBid: '10.00',
[4/10/2020 3:59:23 PM] increments: '15.00',
[4/10/2020 3:59:23 PM] shippingCost: 'Free Shipping',
[4/10/2020 3:59:23 PM] auctionType: 'publicAuction',
[4/10/2020 3:59:23 PM] creator: 5e9076fc2da43424e8e3df82,
[4/10/2020 3:59:23 PM] __v: 0 },
[4/10/2020 3:59:23 PM] bioDescription: 'testtt',
[4/10/2020 3:59:23 PM] bioPicUrl: null ]
but when I JSON.stringify()
the data, the bioDescription and bioPicUrl fields are not included. I tried adding |
delimiter as something I can use .split("|")
function and add ,
to, but it doesn't parse right and I feel like there's an easier way lol. I appreciate any help!
How can I get the data to append and stringify together?
.then(documents => {
documents.bioDescription = artistBioResults.bioDescription;
documents.bioPicUrl = artistBioResults.bioPicUrl;
output = JSON.stringify(documents);
// output = output + "|" + bioDescription + "|" + bioPicUrl;
console.log("OUTPUT");
console.log(documents);
Upvotes: 0
Views: 537
Reputation: 5471
These lines give it away. Note the },
and the ]
[4/10/2020 3:59:23 PM] __v: 0 },
[4/10/2020 3:59:23 PM] bioDescription: 'testtt',
[4/10/2020 3:59:23 PM] bioPicUrl: null ]
You are adding the attributes to an array of documents, not each document in the collection. Try this...
documents.forEach(doc => {
doc.bioDescription = 'test';
doc.bioPicUrl = null;
});
OTOH, if you are actually trying to add properties to the whole array, JSON.stringify() will ignore them since there is no way to put array properties into JSON syntax.
The solution is to wrap theses other properties in an object that includes your array. The following javascript has a JSON representation that wont drop the properties you're interested in keeping.
{ documents: [], bioDescription: 'test', bioPicUrl: null }
Upvotes: 2
Reputation: 7096
documents
is an array.
You can't do this with an array:
documents.documents.bioDescription = something
Upvotes: 0