Skip to content
Advertisement

How to do a join from 2 JSON by a common ID field in Javascript

I have two JSON files: JSON A has some company properties and the company_id, while JSON B has company names and company ids.

JSON A example:

JavaScript

JSONB example:

JavaScript

Which is the most efficient way to do a join by the company_id values? I would like to have the JSON C (merged result) with the company names correctly added, like this:

JavaScript

Is looping and filter for each the only solution? Is there a more efficient way to do this from a performance point of view?

More info:

  • JSON is not sorted by company_id.
  • Array A could have more than one object with the same company_id
  • I’m using Javascript (in a Vue.js app), I don’t need to support old browsers

Advertisement

Answer

In common modern JavaScript, you can do this as you mentioned with higher-order functions like map, filter, and so on:

JavaScript

Note 1: Array.find() method complexity is O(n) and Array.map() method complexity is O(n)

Note 2: efficiency is an important thing but not in all situations. sometimes you need to do these types of iteration one time or for a small array size, so no need to worry about the performance.

Note 3: you could compare the answer and find out your best solution since we don’t know about your whole code and application.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement