简体   繁体   English

如何合并两个json数组的键值对? -Javascript

[英]How to merge the key-value pairs of two json arrays? - Javascript

I have two JSON arrays like this. 我有两个这样的JSON数组。 I want to merge their keyvalue pairs. 我想合并它们的键值对。 They are some items which are common in both while they are some items which are uncommon. 它们是两者共同的一些项目,而它们是不常见的一些项目。

var jsonData1 = [
  {
    firstName: "Sam",
    age: "10"
  },
  {
    firstName: "John",
    age: "11"
  },
  {
    firstName: "Jack",
    age: "12"
  },
  {
    firstName: "Pam",
    age: "13"
  },
  {
    firstName: "Tom",
    age: "14"
  },
  {
    firstName: "Mitch",
    age: "15"
  }
];

var jsonData2 = [
      {
        firstName: "Sam",
        city: "London"
      },
      {
        firstName: "John",
        city: "New York"
      },
      {
        firstName: "Jack",
        city: "Paris"
      },
      {
        firstName: "Pam",
        city: "Moscow"
      },
      {
        firstName: "Roger",
        city: "Shanghai"
      },
      {
        firstName: "Don",
        city: "Jakarta"
      }
    ];

As you can there are some firstName in 1st array which does not have city in 2nd array. 您可以在第一个数组中有一些firstName在第二个数组中没有城市。 Again there are some firstName in 2nd array which does not have city in 1st array. 同样在第二个数组中有一些firstName在第一个数组中没有城市。

I need to club these 2 array into one array, in case a firstName does not have age or city it will be assigned '' (blank string). 我需要将这两个数组合并为一个数组,以防万一firstName没有年龄或城市,它将被分配为”(空白字符串)。

The new array will have 3 fields, there are some items which will be having values in 2 fields. 新数组将具有3个字段,有些项目将在2个字段中具有值。 They have a one field as blank string. 他们有一个字段作为空白字符串。

I want to do this using Vanilla JS, I do not want to use Jquery, Lodash and Underscore. 我想使用Vanilla JS做到这一点,我不想使用Jquery,Lodash和Underscore。

There are a number of ways to approach this, however one option would be to base this around the Array#reduce() method as follows: 有很多方法可以解决此问题,但是一种选择是基于Array#reduce()方法,如下所示:

 const jsonData1=[{firstName:"Sam",age:"10"},{firstName:"John",age:"11"},{firstName:"Jack",age:"12"},{firstName:"Pam",age:"13"},{firstName:"Tom",age:"14"},{firstName:"Mitch",age:"15"}]; const jsonData2=[{firstName:"Sam",city:"London"},{firstName:"John",city:"New York"},{firstName:"Jack",city:"Paris"},{firstName:"Pam",city:"Moscow"},{firstName:"Roger",city:"Shanghai"},{firstName:"Don",city:"Jakarta"}]; /* Use Array#concat() to combine both input arrays before performing the merge. This will ensure that all items in both arrays are processed and accounted for during the merge (which is important in situations where the input arrays differ in length). Object.values() is used to transform the dictionary resulting from reduce() to an array */ var result = Object.values( [].concat(jsonData1, jsonData2 ).reduce((dict, item) => { /* We use Array#reduce is an intermediate step to construct a dictionary which maps each unique "item.firstName" to a corresponding object that contains the merged (or yet to be merged) data for this first name */ var value = dict[item.firstName] || {} /* Use Object.assign() to merge existing data for "item.firstName" with current item being processed. Also pass default values as first argument to ensure all three key values are present in merge result */ value = Object.assign({ firstName : '', age : '', city : ''} , value, item) /* Update the dictionary with merged data */ dict[item.firstName] = value return dict }, {})) console.log(result); 

One possible approach: 一种可能的方法:

 const jsonData1=[{firstName:"Sam",age:"10"},{firstName:"John",age:"11"},{firstName:"Jack",age:"12"},{firstName:"Pam",age:"13"},{firstName:"Tom",age:"14"},{firstName:"Mitch",age:"15"}]; const jsonData2=[{firstName:"Sam",city:"London"},{firstName:"John",city:"New York"},{firstName:"Jack",city:"Paris"},{firstName:"Pam",city:"Moscow"},{firstName:"Roger",city:"Shanghai"},{firstName:"Don",city:"Jakarta"}]; const result = [].concat(jsonData1, jsonData2).reduce((acc, ele) => { const existing = acc.find(x => x.firstName === ele.firstName); if(!existing) return acc.concat({firstName: ele.firstName, city: ele.city || '', age: ele.age || ''}); Object.keys(ele).forEach(x => existing[x] = ele[x]); return acc; },[]) console.log(result); 

I realize you've already accepted an answer but I figured I could provide an alternative, be it better or worse. 我知道您已经接受了答案,但我认为我可以提供替代方案,无论情况好坏。

 var jsonData1 = [{firstName: "Sam",age: "10"},{firstName: "John",age: "11"},{firstName: "Jack",age: "12"},{firstName: "Pam",age: "13"},{firstName: "Tom",age: "14"},{firstName: "Mitch",age: "15"}]; var jsonData2 = [{firstName: "Sam",city: "London"},{firstName: "John",city: "New York"},{firstName: "Jack",city: "Paris"},{firstName: "Pam",city: "Moscow"},{firstName: "Roger",city: "Shanghai"},{firstName: "Don",city: "Jakarta"}]; var defaults = {firstName: "", age: "", city: ""}; var data = [ ...jsonData1, ...jsonData2 ]; var names = [ ...new Set(data.map(i=>i.firstName)) ]; var res = names.map(n => data .reduce((acc, jd) => jd.firstName === n ? {...acc, ...jd} : acc, defaults) ); console.log(res); 

var data combines the two arrays of data into one using spread syntax (array literals) . var data使用扩展语法 (数组文字)将两个数据数组组合为一个。

var names creates an array of unique names using Set . var names使用Set创建一个唯一名称数组。

map() iterates over the list of names, creating a single, merged object for each. map()遍历名称列表,为每个名称创建一个合并的对象。 That merge is done using reduce() and spread syntax (object literals) . 合并是使用reduce()spread语法 (对象文字)完成的

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

相关问题 如何将两个 arrays 合并到具有重复值 javascript 的键值对 - how to merge two arrays to key value pairs with repeated values javascript 如何将JSON数据存储到JavaScript中的键值对中? - how to store JSON data into key-value pairs in javascript? JavaScript:如何构建键值对 - JavaScript: How to build key-value pairs 在Javascript中将对象键值对转换为一系列数组 - Convert object key-value pairs to a series of arrays in Javascript 如何遍历嵌套的JSON对象并在Javascript中保存多个键值对 - How to loop through a nested JSON object and save the multiple key-value pairs in Javascript 如何比较两个对象并获得它们差异的键值对? - How to compare two objects and get key-value pairs of their differences? 如何使用映射的键值对将数组转换为javascript中的对象? - How to convert an array into an object in javascript with mapped key-value pairs? 如何在JavaScript中将多个对象转换为键值对数组[] - How to convert multiple Objects to an Array [] of key-value pairs in javascript 使用 .serializeArray() Javascript 时如何自定义键值对? - How to customize key-value pairs when using .serializeArray() Javascript? 如何将 Object {} 转换为 JavaScript 中键值对的数组 [] - How to convert an Object {} to an Array [] of key-value pairs in JavaScript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM