How to combine these json arrays / objects?

I got a little confused about this question about what an object is, what an array is, and what JSON is. Can someone explain the differences in syntax between the two? and how to add elements to each, how to combine each type, etc.? I am trying to get this function to take new information from a JSON object (I think) and combine it with some new information. This information will then be passed to the PHP script for processing.

Here is the console output:

{"public":{"0":["el29t7","3bmGDy"]}} {"public":"[object Object][object Object]"} 

Here is the JS I'm using:

 /* Helper function to clean up any current data we have stored */ function insertSerializedData(ids, type) { // Get anything in the current field current_data = $('#changes').val(); if (!current_data) { var data = {}; data[index++] = ids; var final_data = {}; final_data[type] = data; $('#changes').val(JSON.stringify(final_data)); } else { current_data = JSON.parse(current_data); var data = {}; data[index++] = ids; // Does the index exist? if (type in current_data) { var temp_data = current_data[type]; current_data[type] = temp_data + data; } else { current_data[type] = data; } //var extra_data = {}; //extra_data[type] = data; //$.merge(current_data, extra_data); $('#changes').val(JSON.stringify(current_data)); } console.log($('#changes').val()); } 

The idea is that the key (public or any other) does not exist yet, and then it points to an array of arrays. However, if it exists, then the array of arrays must be combined with the new array. For instance:

If i have

 {"public":{"0":["el29t7","3bmGDy"]}} 

and I want to combine it with

 ["aj19vA", "jO71Ba"] 

then the end result will be:

 {"public":{"0":["el29t7","3bmGDy"], "1":["aj19vA", "jO71Ba"]}} 

How can i do this? Thanks

+6
source share
5 answers

Great two-part question. In general, the second question is non-trivial due to the complexity of the first.

Question 1:

what is an object, what is an array, and what is JSON. Can someone explain the syntax differences between the two?

Question 2:

and how to add elements to each,

Question 3:

how to combine each type, etc.

Answer 1:

This is a common stumbling block because JavaScript is more flexible than you might have expected at the beginning. Here is the curve.

In JavaScript, everything is an object.

So here is the code for each:

 //What is an object? var obj = { }; var obj2 = { member:"value", myFunction:function(){} } 

Above is an empty object. Then another object with a variable and function. They are called object literals.

 //What is an array var array1 = [ ] ; var array2 = [0,1,2,3,4]; 

Above is an empty array. Then another array with five integers.

Here is a curve that causes confusion.

 //Get elements from each of the prior examples. var x = obj2["member"]; var y = array2[1]; 

What??? Do both objects and the array access the values ​​with a bracket? This is because both are objects. This proves to be good flexibility for writing advanced code. Arrays are objects.

// What is JSON?

JSON stands for JavaScript Object Notiation. As you might have guessed. All this is an object ... It is also { }; But this is different because - it is used to transfer data to - and - from JavaScript, and not to use (usually) in JavaScript. This is a file transfer format.

 var JSONObject = {"member":"value"}; 

The only difference from the previous example is quotation marks. Essentially, we wrap the object literal as a string so that it can be transferred to or from the server, and it can be re-interpreted very easily. Better than XML because it does not need to be manually configured. Just call stringify() or ParseJSON() . Googling it. The fact is that ... JSON can be converted to a literal object of a JS object, and JS objects can be converted to JSON, for example, for transfer to a server or CouchDB database.

Sorry for the tangent.

Answer 2:

How to add an item to each? Here the curve ceases to be a nuisance and begins to be amazing! Since everything is an object, it is all about the same.

 //Add to an object var obj {member1:"stringvalue"} obj.member2 = "addme"; //That is it! //Add to an array var array1 [1,2,3,4,5]; array1[0] = "addme"; array[6] = null; //We shouldn't mix strings, integers, and nulls in arrays, but this isn't a best-practice tutorial. 

Remember the syntax of the JS object, and you can begin to see the whole new flexible world of objects. But it may take a bit.

Answer 3: Ah, yes ... how to merge.

There are serious (very many) ways to merge two arrays. It depends on what you need. Sorting, Duplication, Concatenation ... there are several.

Here is the answer !

UPDATE: how to make a beautiful multi-dimensional array.

 //Multiple Dimension Array var array1 = [1,2,3]; var array2 = [3,4]; var arraysinArray = [array1,array2]; //That is it! 

Here is the curve again, it may be in the object:

 var obj{ array1:[1,2,3], array2:[3,4] } 

JavaScript is powerful material that sticks to it; it gets good. :)

Hope this helps, all the best! Nash

+8
source

In this case, think of the JavaScript literal object {} as an associative array of PHP.

Given that the "array of arrays" actually looks like this (using your desired result):

{public: [["el29t7","3bmGDy"], ["aj19vA", "jO71Ba"]]}

So, here we have an object literal with a single property named "public", whose value is a two-dimensional array.

If we assign the above to a variable, we can then push add another array to "public" as follows:

 var current_data = {public: [["el29t7","3bmGDy"], ["aj19vA", "jO71Ba"]]}; // Using direct property access current_data.public.push(["t9t9t9", "r4r4r4"]); // Or using bracket notation current_data["public"].push(["w2w2w2", "e0e0e0"]); 

current_data now the value:

 {public: [ ["el29t7","3bmGDy"], ["aj19vA", "jO71Ba"], ["t9t9t9", "r4r4r4"], ["w2w2w2", "e0e0e0"] ]} 

So now "public" is an array whose length is 4.

 current_data.public[0]; // ["el29t7","3bmGDy"] current_data.public[1]; // ["aj19vA", "jO71Ba"] current_data.public[2]; // ["t9t9t9", "r4r4r4"] current_data.public[3]; // ["w2w2w2", "e0e0e0"] 

MDN has very good array documentation for understanding other functions that you might need. https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array

+1
source

First it is an object containing an array, the second is an array.

DEMO showing display output http://jsfiddle.net/GjQCV/

 var object={"public":{"0":["el29t7","3bmGDy"]}}; var arr=["aj19vA", "jO71Ba"] ; /* use object notation to add new property and value which is the array*/ object.public[1]=arr; 
0
source

It would be much more natural if {"0": ...} was a true array, not an object, but in any case:

 function maxKey(b) { var max; for( var key in b ) var max = key; return max; } function merge(a,b) { for( var key in a ) { b[key] = b[key] ? (b[key][maxKey(b)+1]=a[key], b[key]) : a[key]; } return b; } 

Note that this assumes that you are inserting into the next integer index

0
source
  • Arrays are a special kind of Javascript object.
  • JSON is a way of representing Javascript objects (and as such can represent arrays and more)
  • Objects are much more general and can be simple objects that can be represented as JSON, or can contain functions and prototypes.

So, this is not an array of arrays (you will access elements using JSON notation, for example myobj ["0"]):

 {"0":["el29t7","3bmGDy"], "1":["aj19vA", "jO71Ba"]} 

This is an array of arrays, which means you can use the push method to add an element and access the elements using array notation like myobj [0]:

 [ ["el29t7","3bmGDy"], ["aj19vA", "jO71Ba"] ] 

It seems that the structure you want looks something like this:

 var myobj = { "public": [ ["key", "value"], ["key", "value"] ] } 

Then, if you want to add / merge new elements, you should write this:

 if (myobj["public"] != null) { myobj["public"].push(["newkey", "newval"]); } else { myobj["public"] = ["newkey", "newval"]; } 
0
source

Source: https://habr.com/ru/post/918812/


All Articles