Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine two nested json objects with javascript and loop through it with a key

I have a few json objects (obj1,obj2...) and each is taken from .txt files:

{
  "countries": [
    {
      "Country name": "China",
      "Flag": "CN",
      "Population": 1395380000,
      "undefined": "#688144"
    }, ... ]}

and

{
  "countries": [
    {
      "Country name": "India",
      "Flag": "IN",
      "Population": 1338677000,
      "undefined": "#B78A31"
    }, ...]}

And so on. Now I want to combine them like this:

{
  "countries": [
    {
      "Country name": "China",
      "Flag": "CN",
      "Population": 1395380000,
      "undefined": "#688144"
    },
 {
      "Country name": "India",
      "Flag": "IN",
      "Population": 1338677000,
      "undefined": "#B78A31"
    },
 ... ]}

So I can loop through data like this:

let obj1 = {}; //saved Data From Txt1;
let obj2 = {}; //saved Data From Txt2
...
let obj = combined?

for (var key in obj.countries) {
var num1 = obj.countries[key].Population+popholder;
if (target >= popholder && target <= num1) {
  var country = obj.countries[key]['Country name'];
  var testas = document.getElementById("countryname")
}}

How could I achieve this?

like image 778
Tomas Am Avatar asked May 03 '26 17:05

Tomas Am


1 Answers

Just concat the arrays:

const obj1 = {
    "countries": [{
            "Country name": "China",
            "Flag": "CN",
            "Population": 1395380000,
            "undefined": "#688144"
        }
    ]
};

const obj2 = {
    "countries": [{
            "Country name": "India",
            "Flag": "IN",
            "Population": 1338677000,
            "undefined": "#B78A31"
        }
    ]
};

const result = {
    countries: [...obj1.countries, ...obj2.countries]
};

console.log(result);
like image 53
Guerric P Avatar answered May 05 '26 06:05

Guerric P



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!