Rod
Rod

Reputation: 15457

How do I merge JSON objects into 1 JSON object

Given:

var result1 = [{'p1':'v1'}];  
var result2 = [{'p2':'v2'}];  
var array1 = [{'p3':'v3'},{'p4':'v4'}];  

Rules:
If array has one property, add property to main array to return.
If array has multiple properties, add a label and keep array as is.

https://jsfiddle.net/3unx0hsa/5/

function mergeJson(data) {  
    let newarray1 = [];

    for (let index = 0; index < resultsArray.length; index++) {
        let element = resultsArray[index][0];

        if (element.length === 1) {            
            newarray1.push(element);
        }

        if (element.length > 1) {
            var x = `{data${index}: ${element}`;
            newarray1.push(x);
        }
    }
}

Illustration: enter image description here

Upvotes: 2

Views: 1372

Answers (3)

Piotr Mirosz
Piotr Mirosz

Reputation: 866

Using that type of function you will be able to display Json values

//JSON = objects and you have to call them for examle:

var result1 = [{'p1':'v1'}];  
var result2 = [{'p2':'v2'}];  
var array1 = result1.concat(result2);
for (i in array1){
 array1[i];
for(x in array1[i]){
document.getElementById("test").innerHTML += x+" - "+array1[i][x] +" <br>";
}
}
<div id="test"></div>

Upvotes: 1

PVDM
PVDM

Reputation: 118

After this line: var x = `{data${index}: ${element}`;, the value for x is a string. That is what you are seeing in you output. Change that line to something like this:

var x = {`{data${index}`: element};

That should give you the result you're expecting.

Upvotes: 1

Yury Tarabanko
Yury Tarabanko

Reputation: 45121

Template string literal creates a string. You need an object literal instead

var x = {[`data${index}`]: element};

var result1 = [{'p1': 'v1'}];
var result2 = [{'p2': 'v2'}];
var array1 = [{'p3': 'v3'}, {'p4': 'v4'}];

let x = mergeJson([result1, result2, array1]);
console.log(x);

function mergeJson(resultsArray) {
  let newarray1 = [];

  for (let index = 0; index < resultsArray.length; index++) {
    let element = resultsArray[index];

    if (element.length === 1) {
      newarray1.push(element[0]);
    }

    if (element.length > 1) {
      var x = {[`data${index}`]: element};
      newarray1.push(x);
    }

  }

  return newarray1;
}

Upvotes: 3

Related Questions