سؤال

I have two objects such as:

{ Count: 1,
  Items:
   [ { foo: [Object],
       name: [Object],
       bar: [Object],
       baz: [Object],
       qux: [Object] } ] }

and

{ Count: 0, Items: [] }

I need to combine them and return one JSON object. However, when I try this, I get

"[object Object][object Object]"

code:

function returnResponse(obj1, obj2) {
            res.statusCode = 200;
            res.setHeader('Content-Type', 'text/plain; charset=UTF-8');
            var returnResult = obj1 + obj2
            res.send(JSON.stringify(returnResult, undefined, 2));
            res.end();
        }

How do I get all the objects to appear correctly in the browser?

هل كانت مفيدة؟

المحلول

I think you're looking to return both objects as an array:

function returnResponse(obj1, obj2) {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain; charset=UTF-8');
    var returnResult = [obj1,obj2];
    res.send(JSON.stringify(returnResult, undefined, 2));
    res.end();
}

نصائح أخرى

If you don't use JS framework like jQuery, you need an recursive merge function. Take a look at this one for example.

You may use $.extend method of jQuery library.

Read more: http://api.jquery.com/jQuery.extend/

Without jQuery, one-liner:

for (var attrname in obj2) { obj1[attrname] = obj2[attrname]; }

Also, this is a duplicate: How can I merge properties of two JavaScript objects dynamically?

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top