This looks like a job for $.map!

var data = {
    "category": [{
          "id": 28,
          "name": "Dogs"
      },
      {
          "id": 14,
          "name": "Cats"
      },
      {
          "id": 878,
          "name": "Sheep"
      }]
}

var cats = $.map(data.category, function(v){
    return v.name;
}).join(', ');
Answer from gen_Eric on Stack Overflow
🌐
techtutorialsx
techtutorialsx.wordpress.com › 2020 › 09 › 06 › javascript-merge-json-objects
JavaScript merge JSON objects – techtutorialsx
January 25, 2025 - In this tutorial we will learn how to merge two JSON objects using JavaScript. We will assume that we are starting from two JSON strings and, at the end, we want to obtain a single JSON string with the merged objects.
🌐
Knowledgewalls
knowledgewalls.com › johnpeter › books › one-day-one-thing-to-know › how-to-mergejoinconcat-json-in-javascript-or-jquery
How to merge-join-concat JSON in Javascript or Jquery?
Everyday one topic to go as master in Future. Book contains technical topics of computer software development. Such as MySQL, Core Java, HTML, CSS and JQuery and More.
🌐
ReqBin
reqbin.com › code › javascript › 9wnknlf8 › javascript-string-concatenation-example
How do I concatenate strings in JavaScript?
This method concatenates the elements of an array and returns a string. The method takes a delimiter as a parameter. If no delimiter is specified, a comma "," is used by default. ... const arr = ['Washington', 'London', 'Madrid']; console.log(arr.join(' ')); // output: Washington London Madrid ... How do I send a POST request using JavaScript? How to send Bearer Token with JavaScript Fetch API? How do I fetch JSON using JavaScript Fetch API?
Top answer
1 of 6
264

There are couple of different solutions to achieve this:

1 - Native javascript for-in loop:

const result = {};
let key;

for (key in obj1) {
  if(obj1.hasOwnProperty(key)){
    result[key] = obj1[key];
  }
}

for (key in obj2) {
  if(obj2.hasOwnProperty(key)){
    result[key] = obj2[key];
  }
}

2 - Object.keys():

const result = {};

Object.keys(obj1)
  .forEach(key => result[key] = obj1[key]);

Object.keys(obj2)
  .forEach(key => result[key] = obj2[key]);

3 - Object.assign():
(Browser compatibility: Chrome: 45, Firefox (Gecko): 34, Internet Explorer: No support, Edge: (Yes), Opera: 32, Safari: 9)

const result = Object.assign({}, obj1, obj2);

4 - Spread Operator:
Standardised from ECMAScript 2015 (6th Edition, ECMA-262):

Defined in several sections of the specification: Array Initializer, Argument Lists

Using this new syntax you could join/merge different objects into one object like this:

const result = {
  ...obj1,
  ...obj2,
};

5 - jQuery.extend(target, obj1, obj2):

Merge the contents of two or more objects together into the first object.

const target = {};

$.extend(target, obj1, obj2);

6 - jQuery.extend(true, target, obj1, obj2):

Run a deep merge of the contents of two or more objects together into the target. Passing false for the first argument is not supported.

const target = {};

$.extend(true, target, obj1, obj2);

7 - Lodash _.assignIn(object, [sources]): also named as _.extend:

const result = {};

_.assignIn(result, obj1, obj2);

8 - Lodash _.merge(object, [sources]):

const result = _.merge(obj1, obj2);

There are a couple of important differences between lodash's merge function and Object.assign:

1- Although they both receive any number of objects but lodash's merge apply a deep merge of those objects but Object.assign only merges the first level. For instance:

_.isEqual(_.merge({
  x: {
    y: { key1: 'value1' },
  },
}, {
  x: {
    y: { key2: 'value2' },
  },
}), {
  x: {
    y: {
      key1: 'value1',
      key2: 'value2',
    },
  },
}); // true

BUT:

const result = Object.assign({
  x: {
    y: { key1: 'value1' },
  },
}, {
  x: {
    y: { key2: 'value2' },
  },
});
_.isEqual(result, {
  x: {
    y: {
      key1: 'value1',
      key2: 'value2',
    },
  },
}); // false
// AND
_.isEqual(result, {
  x: {
    y: {
      key2: 'value2',
    },
  },
}); // true

2- Another difference has to do with how Object.assign and _.merge interpret the undefined value:

_.isEqual(_.merge({x: 1}, {x: undefined}), { x: 1 }) // false

BUT:

_.isEqual(Object.assign({x: 1}, {x: undefined}), { x: undefined })// true

Update 1:

When using for in loop in JavaScript, we should be aware of our environment specially the possible prototype changes in the JavaScript types. For instance some of the older JavaScript libraries add new stuff to Array.prototype or even Object.prototype. To safeguard your iterations over from the added stuff we could use object.hasOwnProperty(key) to mke sure the key is actually part of the object you are iterating over.


Update 2:

I updated my answer and added the solution number 4, which is a new JavaScript feature but not completely standardized yet. I am using it with Babeljs which is a compiler for writing next generation JavaScript.


Update 3:
I added the difference between Object.assign and _.merge.

2 of 6
15

WORKING FIDDLE

Simplest Way with Jquery -

var finalObj = $.extend(obj1, obj2);

Without Jquery -

var finalobj={};
for(var _obj in obj1) finalobj[_obj ]=obj1[_obj];
for(var _obj in obj2) finalobj[_obj ]=obj2[_obj];
Find elsewhere
🌐
Medium
medium.com › @osamakhann118 › string-concatenation-from-json-array-how-to-concatenate-string-from-json-array-b2074ae34927
String Concatenation from JSON Array | How to concatenate string from JSON array - Osama khan - Medium
December 16, 2022 - String Concatenation from JSON Array | How to concatenate string from JSON array If you want to convert a JSON objects array to a concatenated string follow the following process lets say we have a …
🌐
W3Schools
w3schools.com › jsref › jsref_join.asp
JavaScript Array join() Method
❮ Previous JavaScript Array Reference ... "Mango"]; let text = fruits.join(" and "); Try it Yourself » · The join() method returns an array as a string....
Top answer
1 of 3
10

Alasql JavaScript SQL library does exactly what you need in one line:

 <script src="alasql.min.js"></script>
 <script>
    var data = { COLORS: [[1,"red"],[2,"yellow"],[3,"orange"]],            
                 FRUITS: [[1,"apple"],[2,"banana"],[3,"orange"]]};

    data.NEW_FRUITS = alasql('SELECT MATRIX COLORS.[0], COLORS.[1], FRUITS.[1] AS [2] \
         FROM ? AS COLORS JOIN ? AS FRUITS ON COLORS.[0] = FRUITS.[0]',
         [data.COLORS, data.FRUITS]);
 </script>

You can play with this example in jsFiddle.

This is a SQL expression, where:

  • SELECT - select operator
  • MATRIX - modifier, whci converts resultset from array of objects to array of arrays
  • COLORS.[0] - first column of COLORS array, etc.
  • FRUITS.1 AS 2 - the second column of array FRUITS will be stored as third column in resulting recordset
  • FROM ? AS COLORS - data array from parameters named COLORS in SQL statement
  • JOIN ? ON ... - join
  • [data.COLORS, data.FRUITS] - parameters with data arrays
2 of 3
8

The fact that there will be thousands of inputs and the keys are not necessarily ordered means your best bet (at least for large objects) is to sort by key first. For objects of size less than about 5 or so, a brute-force n^2 approach should suffice.

Then you can write out the result by walking through the two arrays in parallel, appending new "records" to your output as you go. This sort-then-merge idea is a relatively powerful one and is used frequently. If you do not want to sort first, you can add elements to a priority queue, merging as you go. The sort-then-merge approach is conceptually simpler to code perhaps; if performance matters you should do some profiling.

For colors-without-fruits and fruits-without-colors, I assume writing null for the missing value is sufficient. If the same key appears more than once in either color or fruit, you can either choose one arbitrarily, or throw an exception.

ADDENDUM I did a fiddle as well: http://jsfiddle.net/LuLMz/. It makes no assumptions on the order of the keys nor any assumptions on the relative lengths of the arrays. The only assumptions are the names of the fields and the fact that each subarray has two elements.

🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Array › join
Array.prototype.join() - JavaScript - MDN Web Docs
The join() method of Array instances creates and returns a new string by concatenating all of the elements in this array, separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.
🌐
Stack Overflow
stackoverflow.com › questions › 44417765 › join-strings-in-js
javascript - join strings in JS - Stack Overflow
The length of array A and B can vary and array B should join the end of array A. What is the best way to do this? I tried using push() but I'm still having problems. Thank you. I did the following to solve the issue · B = JSON.stringify(B); A = A.concat(B); A = A.replace('][', ','); javascript ·