-1

So I have a node endpoint that fetches documents from mongodb. I am seperating data[0] and data[1] into variables because I want to do stuff with it and then chain both back into one varaible and send it.

code:

  const data = await Data.find();
  const data1 = data[0].api.results;
  const data2 = data[1].api.results;
   
  // Do stuff

  const response = data1 + data2;

  res.send(JSON.stringify(response)); // with and without JSON.stringify I still get [object, Object]

Note: both mongodb documents have the exact same structure. Everything works fine if I just send one variable so I think it has to do with JSON.stringify.

user
  • 1,022
  • 2
  • 8
  • 30
  • 3
    What should `data1 + data2` be producing? Because it seems it doesn't contain numbers or strings. – VLAZ Jan 29 '21 at 22:36
  • 3
    Can you clarify exactly what "chain both back into one variable" means? I suspect you might want `const response = [data1, data2]` or something similar to that, but it's unclear. – John Montgomery Jan 29 '21 at 22:40
  • i believe data1 and data2 are javascript object – D. Seah Jan 29 '21 at 22:43
  • @VLAZ it contains objects – user Jan 29 '21 at 23:28
  • Does this answer your question? [How can I merge properties of two JavaScript objects dynamically?](https://stackoverflow.com/questions/171251/how-can-i-merge-properties-of-two-javascript-objects-dynamically) – Mohammad Yaser Ahmadi Jan 29 '21 at 23:40

1 Answers1

2

Here's an example of what's being mentioned in the comments.

const object_1 = { foo: { foo_1: true, foo_2: "test" }, bar: false };
const object_2 = { baz: "hello", bar: [ "one", "two" ] };

let result_1 = object_1 + object_2;
console.log(result_1);
console.log(JSON.stringify(result_1));

let result_2 = [ object_1, object_2 ];
console.log(result_2);
console.log(JSON.stringify(result_2));

Your issue has nothing to do with JSON.stringify. Adding the two objects together won't automatically format them for you.

Instead of data1 + data2, you will either need to stringify an array of the two objects [data1, data2] or merge their properties into a single object.

Here's an example of a simple merge, but note that bar from object_1 was replaced by bar from object_2. Make sure you handle intersections in your objects.

const object_1 = { foo: { foo_1: true, foo_2: "test" }, bar: false };
const object_2 = { baz: "hello", bar: [ "one", "two" ] };

let result = { ...object_1, ...object_2 };
console.log(result);
console.log(JSON.stringify(result));
D M
  • 5,769
  • 4
  • 12
  • 27