I am a bit confused at this point on what is an object, what is an array, and what is a JSON. Can someone explain the differences in syntax between the two? and how to add items to each, how to merge each type, and such? I am trying to get this function to take the new information from a JSON object (I think) and merge it with some new information. This information will then be passed to a PHP script to be processed.
关于什么是对象,什么是数组,什么是JSON,我有点困惑。有人可以解释两者之间的语法差异吗?以及如何向每个项目添加项目,如何合并每种类型,等等?我试图让这个函数从JSON对象中获取新信息(我认为)并将其与一些新信息合并。然后,此信息将传递给要处理的PHP脚本。
Here is the console output:
这是控制台输出:
{"public":{"0":["el29t7","3bmGDy"]}}
{"public":"[object Object][object Object]"}
Here is the JS I am using:
这是我正在使用的JS:
/* 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 if the key (public, or whatever other ones) doesn't exist yet, then to make it point to an array of arrays. If it does exist though, then that of array of arrays need to be merged with a new array. For instance:
这个想法是,如果密钥(公共或其他任何密钥)尚不存在,那么使它指向一个数组数组。如果确实存在,则需要将数组数组与新数组合并。例如:
If I have
如果我有
{"public":{"0":["el29t7","3bmGDy"]}}
and I want to merge it with
我想把它合并
["aj19vA", "jO71Ba"]
then final result would be:
然后最终结果将是:
{"public":{"0":["el29t7","3bmGDy"], "1":["aj19vA", "jO71Ba"]}}
How can i go about doing this? Thanks
我怎么能这样做?谢谢
5 个解决方案
#1
8
Excellent two-part question. Overall, the second question is non-trivial because of the complexity of the first.
优秀的两部分问题。总的来说,第二个问题是非平凡的,因为第一个问题很复杂。
Question 1:
what is an object, what is an array, and what is a JSON. Can someone explain the differences in syntax between the two?
什么是对象,什么是数组,什么是JSON。有人可以解释两者之间的语法差异吗?
Question 2:
and how to add items to each,
以及如何向每个项目添加项目,
Question 3:
how to merge each type, and such?
如何合并每种类型,等等?
Answer 1:
This is a common stumbling point because, JavaScript is more flexible than one might initially expect. Here is the curve.
这是一个常见的绊脚石,因为JavaScript比最初期望的更灵活。这是曲线。
In JavaScript everything is an object.
在JavaScript中,一切都是对象。
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 a 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 the curve that causes confusion.
这是引起混淆的曲线。
//Get elements from each of the prior examples.
var x = obj2["member"];
var y = array2[1];
What??? Both Object and Array are accessing values with a bracket? This is because both are objects. This turns out to be a nice flexibility for writing advanced code. Arrays are objects.
什么??? Object和Array都使用括号访问值?这是因为两者都是对象。这对于编写高级代码来说是一个很好的灵活性。数组是对象。
//What is JSON?
//什么是JSON?
JSON stands for JavaScript Object Notiation. As you might have guessed. Everything is an object... It is also an { };
But it is different because - it is used to transfer data to - and - from JavaScript, not actually used (commonly) in JavaScript. It is a file transfer format.
JSON代表JavaScript Object Notiation。你可能已经猜到了。一切都是一个对象......它也是一个{};但它有所不同,因为 - 它用于将数据传输到 - 和 - 从JavaScript传输,而不是在JavaScript中实际使用(通常)。它是一种文件传输格式。
var JSONObject = {"member":"value"};
The only difference to the prior example is quotes. Essentially we are wrapping the object literal as a string so that it can be transferred to a server, or back, and it can be reinterpreted, very easily. Better than XML - because it does not have to be custom-parsed. Just call, stringify()
or ParseJSON()
. Google it. The point is... JSON can be converted into an object-literal JS object, and JS object-literals can be converted into JSON, for transfer to a server or a CouchDB database, for example.
与前一个例子的唯一区别是引用。本质上,我们将对象文字包装为字符串,以便可以将其传输到服务器或返回,并且可以非常轻松地重新解释。比XML更好 - 因为它不必自定义解析。只需调用stringify()或ParseJSON()即可。去谷歌上查询。重点是......例如,JSON可以转换为对象文字JS对象,JS对象文字可以转换为JSON,以便传输到服务器或CouchDB数据库。
Sorry for the tangent.
对不起切线。
Answer 2:
How to add an item to each? Here is where the curve stops being a nuisance, and starts being awesome! Because everything is an object, it is all just 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 JS object syntax and you may start to see a whole new flexible world of objects open up. But it may take a bit.
记住JS对象的语法,你可能会开始看到一个全新的灵活的对象世界。但可能需要一点时间。
Answer 3: Ah, yeah... how to merge.
答案3:啊,是的......如何合并。
There are seriously (very many) ways to merge two arrays. It depends on exactly what you need. Sorted, Duplicated, Concatenated... there are a few.
合并两个数组的方法非常多(非常多)。这取决于你需要什么。排序,重复,连接......有一些。
这是答案!
UPDATE: How to make a beautiful multiple 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, this could be in an object:
这是曲线,这可能是一个对象:
var obj{
array1:[1,2,3],
array2:[3,4]
}
JavaScript is powerful stuff, stick with it; it gets good. : )
JavaScript是强大的东西,坚持下去;它变得很好。 :)
Hope that helps, All the best! Nash
希望有所帮助,一切顺利!纳什
#2
1
In this case, think of a JavaScript's object literal {}
as being like PHP's associative array.
在这种情况下,将JavaScript的对象文字{}视为PHP的关联数组。
Given that, an "array of arrays" actually looks like this (using your above desired output):
鉴于此,“数组数组”实际上看起来像这样(使用您上面想要的输出):
{public: [["el29t7","3bmGDy"], ["aj19vA", "jO71Ba"]]}
{public:[[“el29t7”,“3bmGDy”],[“aj19vA”,“jO71Ba”]]}
So here we have an object literal with a single property named "public" whose value is a 2-dimensional array.
所以这里我们有一个对象文字,它有一个名为“public”的属性,其值是一个二维数组。
If we assign the above to a variable we can then push
another array onto "public" like this:
如果我们将上面的内容分配给变量,我们可以将另一个数组推送到“public”,如下所示:
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
's value is now:
current_data的值现在是:
{public: [
["el29t7","3bmGDy"],
["aj19vA", "jO71Ba"],
["t9t9t9", "r4r4r4"],
["w2w2w2", "e0e0e0"]
]}
So now "public" is an array whose length is 4.
所以现在“public”是一个长度为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 documentation on Array for insight on other functions you might need. https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array
MDN拥有非常好的Array文档,可以深入了解您可能需要的其他功能。 https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array
#3
0
First is an object, that contains array, second is an array.
首先是一个对象,它包含数组,第二个是数组。
DEMO showing display output http://jsfiddle.net/GjQCV/
DEMO显示显示输出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;
#4
0
It'd be much more natural if {"0": ...}
were a true array rather than an object, but anyway:
如果{“0”:...}是一个真正的数组而不是一个对象,那就更自然了,但无论如何:
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 you would insert at the next integer index
请注意,这假设您将插入下一个整数索引
#5
0
- Arrays are a particular 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.
数组是一种特殊的Javascript对象
JSON是一种表示Javascript对象的方式(因此可以表示数组等)
对象更通用,可以是可以表示为JSON的简单对象,也可以包含函数和原型。
So, this is not an array of arrays (you would access items using JSON notation like myobj["0"]):
所以,这不是一个数组数组(您可以使用JSON表示法访问项目,如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 item, and access items using array notation like myobj[0]:
这是一个数组数组,这意味着您可以使用push方法添加项目,并使用数组表示法访问项目,如myobj [0]:
[ ["el29t7","3bmGDy"], ["aj19vA", "jO71Ba"] ]
It seems like the structure you want is something like this:
看起来你想要的结构是这样的:
var myobj = { "public": [ ["key", "value"], ["key", "value"] ] }
Then if you want to add/merge new items, you'd write this:
然后,如果你想添加/合并新项目,你可以这样写:
if (myobj["public"] != null) {
myobj["public"].push(["newkey", "newval"]);
} else {
myobj["public"] = ["newkey", "newval"];
}
#1
8
Excellent two-part question. Overall, the second question is non-trivial because of the complexity of the first.
优秀的两部分问题。总的来说,第二个问题是非平凡的,因为第一个问题很复杂。
Question 1:
what is an object, what is an array, and what is a JSON. Can someone explain the differences in syntax between the two?
什么是对象,什么是数组,什么是JSON。有人可以解释两者之间的语法差异吗?
Question 2:
and how to add items to each,
以及如何向每个项目添加项目,
Question 3:
how to merge each type, and such?
如何合并每种类型,等等?
Answer 1:
This is a common stumbling point because, JavaScript is more flexible than one might initially expect. Here is the curve.
这是一个常见的绊脚石,因为JavaScript比最初期望的更灵活。这是曲线。
In JavaScript everything is an object.
在JavaScript中,一切都是对象。
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 a 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 the curve that causes confusion.
这是引起混淆的曲线。
//Get elements from each of the prior examples.
var x = obj2["member"];
var y = array2[1];
What??? Both Object and Array are accessing values with a bracket? This is because both are objects. This turns out to be a nice flexibility for writing advanced code. Arrays are objects.
什么??? Object和Array都使用括号访问值?这是因为两者都是对象。这对于编写高级代码来说是一个很好的灵活性。数组是对象。
//What is JSON?
//什么是JSON?
JSON stands for JavaScript Object Notiation. As you might have guessed. Everything is an object... It is also an { };
But it is different because - it is used to transfer data to - and - from JavaScript, not actually used (commonly) in JavaScript. It is a file transfer format.
JSON代表JavaScript Object Notiation。你可能已经猜到了。一切都是一个对象......它也是一个{};但它有所不同,因为 - 它用于将数据传输到 - 和 - 从JavaScript传输,而不是在JavaScript中实际使用(通常)。它是一种文件传输格式。
var JSONObject = {"member":"value"};
The only difference to the prior example is quotes. Essentially we are wrapping the object literal as a string so that it can be transferred to a server, or back, and it can be reinterpreted, very easily. Better than XML - because it does not have to be custom-parsed. Just call, stringify()
or ParseJSON()
. Google it. The point is... JSON can be converted into an object-literal JS object, and JS object-literals can be converted into JSON, for transfer to a server or a CouchDB database, for example.
与前一个例子的唯一区别是引用。本质上,我们将对象文字包装为字符串,以便可以将其传输到服务器或返回,并且可以非常轻松地重新解释。比XML更好 - 因为它不必自定义解析。只需调用stringify()或ParseJSON()即可。去谷歌上查询。重点是......例如,JSON可以转换为对象文字JS对象,JS对象文字可以转换为JSON,以便传输到服务器或CouchDB数据库。
Sorry for the tangent.
对不起切线。
Answer 2:
How to add an item to each? Here is where the curve stops being a nuisance, and starts being awesome! Because everything is an object, it is all just 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 JS object syntax and you may start to see a whole new flexible world of objects open up. But it may take a bit.
记住JS对象的语法,你可能会开始看到一个全新的灵活的对象世界。但可能需要一点时间。
Answer 3: Ah, yeah... how to merge.
答案3:啊,是的......如何合并。
There are seriously (very many) ways to merge two arrays. It depends on exactly what you need. Sorted, Duplicated, Concatenated... there are a few.
合并两个数组的方法非常多(非常多)。这取决于你需要什么。排序,重复,连接......有一些。
这是答案!
UPDATE: How to make a beautiful multiple 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, this could be in an object:
这是曲线,这可能是一个对象:
var obj{
array1:[1,2,3],
array2:[3,4]
}
JavaScript is powerful stuff, stick with it; it gets good. : )
JavaScript是强大的东西,坚持下去;它变得很好。 :)
Hope that helps, All the best! Nash
希望有所帮助,一切顺利!纳什
#2
1
In this case, think of a JavaScript's object literal {}
as being like PHP's associative array.
在这种情况下,将JavaScript的对象文字{}视为PHP的关联数组。
Given that, an "array of arrays" actually looks like this (using your above desired output):
鉴于此,“数组数组”实际上看起来像这样(使用您上面想要的输出):
{public: [["el29t7","3bmGDy"], ["aj19vA", "jO71Ba"]]}
{public:[[“el29t7”,“3bmGDy”],[“aj19vA”,“jO71Ba”]]}
So here we have an object literal with a single property named "public" whose value is a 2-dimensional array.
所以这里我们有一个对象文字,它有一个名为“public”的属性,其值是一个二维数组。
If we assign the above to a variable we can then push
another array onto "public" like this:
如果我们将上面的内容分配给变量,我们可以将另一个数组推送到“public”,如下所示:
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
's value is now:
current_data的值现在是:
{public: [
["el29t7","3bmGDy"],
["aj19vA", "jO71Ba"],
["t9t9t9", "r4r4r4"],
["w2w2w2", "e0e0e0"]
]}
So now "public" is an array whose length is 4.
所以现在“public”是一个长度为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 documentation on Array for insight on other functions you might need. https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array
MDN拥有非常好的Array文档,可以深入了解您可能需要的其他功能。 https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array
#3
0
First is an object, that contains array, second is an array.
首先是一个对象,它包含数组,第二个是数组。
DEMO showing display output http://jsfiddle.net/GjQCV/
DEMO显示显示输出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;
#4
0
It'd be much more natural if {"0": ...}
were a true array rather than an object, but anyway:
如果{“0”:...}是一个真正的数组而不是一个对象,那就更自然了,但无论如何:
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 you would insert at the next integer index
请注意,这假设您将插入下一个整数索引
#5
0
- Arrays are a particular 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.
数组是一种特殊的Javascript对象
JSON是一种表示Javascript对象的方式(因此可以表示数组等)
对象更通用,可以是可以表示为JSON的简单对象,也可以包含函数和原型。
So, this is not an array of arrays (you would access items using JSON notation like myobj["0"]):
所以,这不是一个数组数组(您可以使用JSON表示法访问项目,如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 item, and access items using array notation like myobj[0]:
这是一个数组数组,这意味着您可以使用push方法添加项目,并使用数组表示法访问项目,如myobj [0]:
[ ["el29t7","3bmGDy"], ["aj19vA", "jO71Ba"] ]
It seems like the structure you want is something like this:
看起来你想要的结构是这样的:
var myobj = { "public": [ ["key", "value"], ["key", "value"] ] }
Then if you want to add/merge new items, you'd write this:
然后,如果你想添加/合并新项目,你可以这样写:
if (myobj["public"] != null) {
myobj["public"].push(["newkey", "newval"]);
} else {
myobj["public"] = ["newkey", "newval"];
}