简体   繁体   English

如何合并这些数组/ json对象?

[英]How to merge these arrays/json objects?

I am a bit confused at this point on what is an object, what is an array, and what is a JSON. 关于什么是对象,什么是数组,什么是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. 我试图让这个函数从JSON对象中获取新信息(我认为)并将其与一些新信息合并。 This information will then be passed to a PHP script to be processed. 然后,此信息将传递给要处理的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 谢谢

Excellent two-part question. 优秀的两部分问题。 Overall, the second question is non-trivial because of the complexity of the first. 总的来说,第二个问题是非平凡的,因为第一个问题很复杂。

Question 1: 问题1:

what is an object, what is an array, and what is a JSON. 什么是对象,什么是数组,什么是JSON。 Can someone explain the differences in syntax between the two? 有人可以解释两者之间的语法差异吗?

Question 2: 问题2:

and how to add items to each, 以及如何向每个项目添加项目,

Question 3: 问题3:

how to merge each type, and such? 如何合并每种类型,等等?

Answer 1: 答案1:

This is a common stumbling point because, JavaScript is more flexible than one might initially expect. 这是一个常见的绊脚石,因为JavaScript比最初期望的更灵活。 Here is the curve. 这是曲线。

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? Object和Array都使用括号访问值? This is because both are objects. 这是因为两者都是对象。 This turns out to be a nice flexibility for writing advanced code. 这对于编写高级代码来说是一个很好的灵活性。 Arrays are objects. 数组是对象。

//What is JSON? //什么是JSON?

JSON stands for JavaScript Object Notiation. JSON代表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. 但它有所不同,因为 - 它用于将数据传输到 - 和 - 从JavaScript传输,而不是 JavaScript中实际使用(通常)。 It is a file transfer format. 它是一种文件传输格式。

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. 优于XML - 因为它不必自定义解析。 Just call, stringify() or ParseJSON() . 只需调用, stringify()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. 重点是......例如,JSON可以转换为对象文字JS对象,JS对象文字可以转换为JSON,以便传输到服务器或CouchDB数据库。

Sorry for the tangent. 对不起切线。

Answer 2: 答案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. 记住JS对象语法,你可能会开始看到一个全新的灵活的对象世界。 But it may take a bit. 但可能需要一点时间。

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. 排序,重复,连接......有一些。

Here is the answer ! 这是答案

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; JavaScript是强大的东西,坚持下去; it gets good. 它变得很好。 : ) :)

Hope that helps, All the best! 希望有所帮助,一切顺利! Nash 纳什

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"]]}

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: 如果我们将上面的内容分配给变量,我们可以push另一个数组push送到“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. MDN在Array上有非常好的文档,可以深入了解您可能需要的其他功能。 https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array

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;

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 请注意,这假设您将插入下一个整数索引

  1. Arrays are a particular kind of Javascript object 数组是一种特殊的Javascript对象
  2. JSON is a way of representing Javascript objects (and as such can represent arrays and more) JSON是一种表示Javascript对象的方式(因此可以表示数组等)
  3. Objects are much more general, and can be simple objects that can be represented as JSON, or can contain functions and prototypes. 对象更通用,可以是可以表示为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"];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM