将两个 json/javascript 数组合并为一个数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10384845/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:06:58  来源:igfitidea点击:

Merge two json/javascript arrays in to one array

javascriptjqueryjson

提问by Murtaza Khursheed Hussain

I have two json arrays like

我有两个 json 数组,例如

var json1 = [{id:1, name: 'xxx' ...}]
var json2 = [{id:2, name: 'xyz' ...}]

I want them merge in to single arrays

我希望它们合并为单个数组

var finalObj = [{id:1, name: 'xxx' ...},{id:2, name: 'xyz' ...}]

回答by Quentin

You want the concatmethod.

你想要concat方法。

var finalObj = json1.concat(json2);

回答by SpYk3HH

Upon first appearance, the word "merg" leads one to think you need to use .extend, which is the proper jQuery way to "merge" JSON objects. However, $.extend(true, {}, json1, json2);will cause all values sharing the same key name to be overridden by the latest supplied in the params. As review of your question shows, this is undesired.

第一次出现时,“合并”这个词让人认为您需要使用.extend,这是“合并”JSON 对象的正确 jQuery 方式。但是,$.extend(true, {}, json1, json2);将导致共享相同键名的所有值被参数中提供的最新值覆盖。正如对您的问题的所示,这是不受欢迎的。

What you seek is a simple javascript function known as .concat. Which would work like:

您要寻找的是一个简单的 javascript 函数,称为.concat。这会像:

var finalObj = json1.concat(json2);

While this is not a native jQuery function, you could easily add it to the jQuery library for simple future use as follows:

虽然这不是原生 jQuery 函数,但您可以轻松地将它添加到 jQuery 库中,以便将来简单使用,如下所示:

;(function($) {
    if (!$.concat) {
        $.extend({
            concat: function() {
                return Array.prototype.concat.apply([], arguments);
            }
        });
    }
})(jQuery);

And then recall it as desired like:

然后根据需要调用它,例如:

var finalObj = $.concat(json1, json2);

You can also use it for multiple array objects of this type with a like:

您还可以将它用于这种类型的多个数组对象,例如:

var finalObj = $.concat(json1, json2, json3, json4, json5, ....);

And if you really want it jQuery style and very short and sweet (aka minified)

如果你真的想要它 jQuery 风格和非常简短和甜蜜(又名缩小)

;(function(a){a.concat||a.extend({concat:function(){return Array.prototype.concat.apply([],arguments);}})})(jQuery);

;(function($){$.concat||$.extend({concat:function(){return Array.prototype.concat.apply([],arguments);}})})(jQuery);

$(function() {
    var json1 = [{id:1, name: 'xxx'}],
        json2 = [{id:2, name: 'xyz'}],
        json3 = [{id:3, name: 'xyy'}],
        json4 = [{id:4, name: 'xzy'}],
        json5 = [{id:5, name: 'zxy'}];
    
    console.log(Array(10).join('-')+'(json1, json2, json3)'+Array(10).join('-'));
    console.log($.concat(json1, json2, json3));
    console.log(Array(10).join('-')+'(json1, json2, json3, json4, json5)'+Array(10).join('-'));
    console.log($.concat(json1, json2, json3, json4, json5));
    console.log(Array(10).join('-')+'(json4, json1, json2, json5)'+Array(10).join('-'));
    console.log($.concat(json4, json1, json2, json5));
});
center { padding: 3em; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<center>See Console Log</center>

jsFiddle

js小提琴

回答by izb

You could try merge

你可以尝试合并

var finalObj = $.merge(json1, json2);

回答by Kris Krause

Since you are using jQuery. How about the jQuery.extend() method?

由于您使用的是 jQuery。jQuery.extend() 方法怎么样?

http://api.jquery.com/jQuery.extend/

http://api.jquery.com/jQuery.extend/

Description: Merge the contents of two or more objects together into the first object.

描述:将两个或多个对象的内容合并到第一个对象中。

回答by Hoque MD Zahidul

You can do this using Es 6 new feature :

您可以使用 Es 6 新功能执行此操作:

var json1 = [{id:1, name: 'xxx' , ocupation : 'Doctor' }];

var json2 = [{id:2, name: 'xyz' ,ocupation : 'SE'}];

var combineJsonArray = [...json1 , ...json2];

//output should like this [ { id: 1, name: 'xxx', ocupation: 'Doctor' },
  { id: 2, name: 'xyz', ocupation: 'SE' } ]

Or You can put extra string or anything between two json array :

或者您可以在两个 json 数组之间放置额外的字符串或任何内容:

var json3 = [...json1 ,"test", ...json2];

// output should like this : [ { id: 1, name: 'xxx', ocupation: 'Doctor' },
  'test',
  { id: 2, name: 'xyz', ocupation: 'SE' } ]

回答by Jér?me B

Maybe, you can use the array syntax of javascript :

也许,您可以使用 javascript 的数组语法:

var finalObj =[json1 , json2]

回答by Penny Liu

You can achieve this using Lodash_.mergefunction.

您可以使用Lodash_.merge函数来实现这一点

var json1 = [{id:1, name: 'xxx'}];
var json2 = [{id:2, name: 'xyz'}];
var merged = _.merge(_.keyBy(json1, 'id'), _.keyBy(json2, 'id'));
var finalObj = _.values(merged);

console.log(finalObj);
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>

回答by Mailyan

You can use the new js spread operator if using es6:

如果使用 es6,您可以使用新的 js 扩展运算符:

var json1 = [{id:1, name: 'xxx'}]
var json2 = [{id:2, name: 'xyz'}]
var finalObj = [...json1, ...json2]

console.log(finalObj)

回答by DEEPAK PRABHU

Try the code below, using jQuery extend method:

试试下面的代码,使用 jQuery 扩展方法:

var json1 = {"name":"ramesh","age":"12"};

var json2 = {"member":"true"};

document.write(JSON.stringify($.extend(true,{},json1,json2)))

回答by Vinoth Smart

var json1=["Chennai","Bangalore"];
var json2=["TamilNadu","Karanataka"];

finaljson=json1.concat(json2);