简体   繁体   English

如何在不使用JQUERY的情况下联接两个JavaScript数组的JSON对象?

[英]How to join two JavaScript arrays of JSON Objects, without using JQUERY?

I have two arrays of objects (If I am not using proper terminology, please forgive me. I am new to JS). 我有两个对象数组(如果我使用的术语不正确,请原谅我。我是JS的新手)。 The arrays dataset and dataset2 , have objects with a common key id . 该阵列datasetdataset2 ,有一个共同的关键对象id I want to merge each object to form a new array of merged objects. 我想合并每个对象以形成合并对象的新数组。 As shown in datasetCombined below. 如下面的datasetCombined所示。

dataset = [{​
    "State": "AL",
    "id": 1000,
    "name": "Alabama",​​
    "percent_educated": 24},

    {​
    "State": "AL",
    "id": 1001,
    "name": "Autauga County",​​
    "percent_educated": 24.6},

    {​
    "State": "AL",
    "id": 1003,
    "name": "Baldwin County",​​
    "percent_educated": 29.5
    }]

dataset2 = [{​
    "id": 1000,
    "qualified_professionals": "64,767,787",​​
    "high_school": "58,820,411",
    "middle_school_or_lower": "27,818,380" },

    {
    "id": 1001,
    "qualified_professionals": "783,076",​​
    "high_school": "1,009,593",
    "middle_school_or_lower": "496,036" },

    {​
    "id": 1003,
    "qualified_professionals": "8,968",​​
    "high_school": "12,519",
    "middle_school_or_lower": "4,528" 
    }]

Desired Output: 所需输出:

datasetCombined = [{​
    "State": "AL",
    "id": 1000,
    "name": "Alabama",​​
    "percent_educated": 24,
    "qualified_professionals": "64,767,787",​​
    "high_school": "58,820,411",
    "middle_school_or_lower": "27,818,380"},

    {​
    "State": "AL",
    "id": 1001,
    "name": "Autauga County",​​
    "percent_educated": 24.6,
    "qualified_professionals": "783,076",​​
    "high_school": "1,009,593",
    "middle_school_or_lower": "496,036"},

    {​
    "State": "AL",
    "id": 1003,
    "name": "Baldwin County",​​
    "percent_educated": 29.5,
    "qualified_professionals": "8,968",​​
    "high_school": "12,519",
    "middle_school_or_lower": "4,528"
    }]

A possible solution to the above problem could be: 上述问题的可能解决方案可能是:

Object.assign(b, a);

This way b would have both its own properties and a's properties. 这样,b将同时具有其自身的属性和a的属性。 However, we might want to avoid modifying b. 但是,我们可能要避免修改b。 In such a case, we can introduce a new, empty object and copy properties from a and b to it. 在这种情况下,我们可以引入一个新的空对象并将属性从a和b复制到它。

const c = Object.assign({}, a, b);

And If for some reason you cannot use ES6 language features in your application, you can resort to using the Lodash library. 并且,如果由于某种原因您无法在应用程序中使用ES6语言功能,则可以诉诸于使用Lodash库。

const c = _.assign({}, a, b);

After the blunder with misreading your question I spent a bit of time and built this example for you to merge the two arrays based on the Id. 在错误地理解了您的问题之后,我花了一些时间并为您构建了此示例,以便您根据ID合并两个数组。

 let dataset = [{ "State": "AL", "id": 1000, "name": "Alabama", "percent_educated": 24 }, { "State": "AL", "id": 1001, "name": "Autauga County", "percent_educated": 24.6 }, { "State": "AL", "id": 1003, "name": "Baldwin County", "percent_educated": 29.5 } ]; let dataset2 = [{ "id": 1000, "qualified_professionals": "64,767,787", "high_school": "58,820,411", "middle_school_or_lower": "27,818,380" }, { "id": 1001, "qualified_professionals": "783,076", "high_school": "1,009,593", "middle_school_or_lower": "496,036" }, { "id": 1003, "qualified_professionals": "8,968", "high_school": "12,519", "middle_school_or_lower": "4,528" } ]; // create a function to reduce your arrays let reducer = function(accumulator, currentValue, currentIndex, array) { // check if the item already exists in the array let found = accumulator.find((item) => item.id == currentValue.id); if (found) { // if it exists then use assign to merge the two values Object.assign(found, currentValue) } else { // doesn't exist, just add it to the array accumulator.push(currentValue); } return accumulator; } let datasetCombined = []; dataset.reduce(reducer, datasetCombined); dataset2.reduce(reducer, datasetCombined); console.log(datasetCombined); 

You could use Array.prototype.reduce: 您可以使用Array.prototype.reduce:

const datasetCombined = dataset1.reduce((acc, next) => {
    const combinedItem = Object.assign(
        {},
        next,
        dataset2.find(item => (item.id = next.id))
    );
    acc.push(combinedItem);
    return acc;
}, []);

You could look for the id and append an existing object or push a copy of the object to the result set. 您可以查找id并附加一个现有对象或将该对象的副本推送到结果集中。

This works for an arbitrary count of arrays. 这适用于任意数量的数组。

 var dataset = [{ State: "AL", id: 1000, name: "Alabama", percent_educated: 24 }, { State: "AL", id: 1001, name: "Autauga County", percent_educated: 24.6 }, { State: "AL", id: 1003, name: "Baldwin County", percent_educated: 29.5 }], dataset2 = [{ id: 1000, qualified_professionals: "64,767,787", high_school: "58,820,411", middle_school_or_lower: "27,818,380" }, { id: 1001, qualified_professionals: "783,076", high_school: "1,009,593", middle_school_or_lower: "496,036" }, { id: 1003, qualified_professionals: "8,968", high_school: "12,519", middle_school_or_lower: "4,528" }], result = [dataset, dataset2].reduce((r, a) => { a.forEach(o => { var temp = r.find(({ id }) => o.id === id); if (!temp) { r.push(Object.assign({}, o)); } else { Object.assign(temp, o); } }); return r; }, []); console.log(result); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

A slightly better approach with a Map . 使用Map更好的方法。

 var dataset = [{ State: "AL", id: 1000, name: "Alabama", percent_educated: 24 }, { State: "AL", id: 1001, name: "Autauga County", percent_educated: 24.6 }, { State: "AL", id: 1003, name: "Baldwin County", percent_educated: 29.5 }], dataset2 = [{ id: 1000, qualified_professionals: "64,767,787", high_school: "58,820,411", middle_school_or_lower: "27,818,380" }, { id: 1001, qualified_professionals: "783,076", high_school: "1,009,593", middle_school_or_lower: "496,036" }, { id: 1003, qualified_professionals: "8,968", high_school: "12,519", middle_school_or_lower: "4,528" }], result = Array.from([dataset, dataset2].reduce( (r, a) => a.reduce((m, o) => m.set(o.id, Object.assign(m.get(o.id) || {}, o)), r), new Map ).values()); console.log(result); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

Try this with Underscore.js or Lodash 用试试这个Underscore.jsLodash

var mergedList = _.map(dataset1, function(item){
  return _.extend(item, _.findWhere(dataset2, { 
    id: item.id 
  })); 
});

If you are not using ES6 and you don't want to use any library like Lodash , and If The number of objects in both arrays are equal and they are in order by the id property (as shown in your example), then you can use the code bellow: 如果您没有使用ES6并且不想使用任何类似Lodash库,并且如果两个数组中的对象数相等并且它们按id属性排序(如示例所示),则可以使用下面的代码:

var datasetCombined = [];

dataset.map(function(obj,keyNo){
  for (var key in dataset2[keyNo]){
    obj[key]=dataset2[keyNo][key];
  }
  datasetCombined.push(obj)
});

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

相关问题 使用jQuery比较两个Javascript对象数组 - Using jQuery to compare two arrays of Javascript objects 如何在JavaScript中连接两个对象数组? - How can I join two arrays of objects in JavaScript? 如何使用属性作为主键左连接 arrays 的两个 javascript 对象? - How can I left join two javascript objects of arrays using properties as primary keys? 使用 JavaScript,如何根据列名数组连接两个 arrays 对象? - Using JavaScript, how to join two arrays of objects based on array of column names? 如何合并两个JSON对象数组 - 删除重复项并保留Javascript / jQuery中的顺序? - How to merge two arrays of JSON objects - removing duplicates and preserving order in Javascript/jQuery? 如何使用 JavaScript 中的 ID 加入两个关联 arrays? - How to join with two associative arrays using an ID in JavaScript? Javascript - 加入对象的 arrays - Javascript - join arrays of objects 使用函数式编程连接两个JSON对象数组(例如SQL连接) - Joining two arrays of JSON objects like an SQL join using functional programming 如何使用jQuery在两个数组中选择相同的对象? - How to select same objects in two arrays using jQuery? 如何使用sailsjs-nodejs合并/合并两个json对象 - How to join/merge two json objects using sailsjs-nodejs
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM