【问题标题】:Merge two array of objects based on a key根据键合并两个对象数组
【发布时间】:2022-12-15 07:56:07
【问题描述】:

我有两个数组:

阵列 1:

[
  { id: "abdc4051", date: "2017-01-24" }, 
  { id: "abdc4052", date: "2017-01-22" }
]

和阵列 2:

[
  { id: "abdc4051", name: "ab" },
  { id: "abdc4052", name: "abc" }
]

我需要根据 id 合并这两个数组并得到这个:

[
  { id: "abdc4051", date: "2017-01-24", name: "ab" },
  { id: "abdc4052", date: "2017-01-22", name: "abc" }
]

我如何在不遍历Object.keys的情况下做到这一点?

【问题讨论】:

  • 数组是否总是排序并且对相同的id 具有相同的索引?
  • 这就是我要做的:array1.map(x => { return array2.map(y => { if (y.id === x.id) { x.date = y.date; return x; } } }
  • @Thadeus Ajayi - 这比打勾的答案提供的方法更正确。只需如下所示填充缺少的括号 array1.map((x) => array2.map((y) => { if (y.id === x.id) { x.date = y.date; 返回 x; } }) );
  • @ThadeusAjayi 你能解释一下为什么你有 x.date = y.date 吗?那有什么作用?我不太了解 Array.map。
  • @Jknight 我猜它应该是 x.name = y.name 因为那是需要更新的字段。

标签: javascript


【解决方案1】:

你可以这样做 -

let arr1 = [
    { id: "abdc4051", date: "2017-01-24" },
    { id: "abdc4052", date: "2017-01-22" }
];

let arr2 = [
    { id: "abdc4051", name: "ab" },
    { id: "abdc4052", name: "abc" }
];

let arr3 = arr1.map((item, i) => Object.assign({}, item, arr2[i]));

console.log(arr3);

如果 arr1arr2 的顺序不同,请使用以下代码:

let arr1 = [
  { id: "abdc4051", date: "2017-01-24" }, 
  { id: "abdc4052", date: "2017-01-22" }
];

let arr2 = [
  { id: "abdc4051", name: "ab" },
  { id: "abdc4052", name: "abc" }
];

let merged = [];

for(let i=0; i<arr1.length; i++) {
  merged.push({
   ...arr1[i], 
   ...(arr2.find((itmInner) => itmInner.id === arr1[i].id))}
  );
}

console.log(merged);

如果arr1arr2 的顺序相同,则使用此选项

let arr1 = [
  { id: "abdc4051", date: "2017-01-24" }, 
  { id: "abdc4052", date: "2017-01-22" }
];

let arr2 = [
  { id: "abdc4051", name: "ab" },
  { id: "abdc4052", name: "abc" }
];

let merged = [];

for(let i=0; i<arr1.length; i++) {
  merged.push({
   ...arr1[i], 
   ...arr2[i]
  });
}

console.log(merged);

【讨论】:

  • 这只是合并数组?它不会像 OP 所要求的那样在 arr1.id == arr2.id 上“加入”。
  • 标题是“根据一个键合并两个对象数组”。 OP还在“基于id”的帖子中提到。
  • 这不尊重键/键值。它只是合并数组中的每个项目。问题是:如何按键合并两个数组。对于 arr1,您必须通过键“id”从 arr2 中找到正确的项目。
  • @Dominik 根据 OP 的要求更新了答案。
  • 请注意一件事,这两个数组必须具有完全相同数量的数据和键。如果一个有 2 个键,另一个有 3 个键,它将不起作用。
【解决方案2】:

你可以一行完成

let arr1 = [
    { id: "abdc4051", date: "2017-01-24" },
    { id: "abdc4052", date: "2017-01-22" }
];

let arr2 = [
    { id: "abdc4051", name: "ab" },
    { id: "abdc4052", name: "abc" }
];

const mergeById = (a1, a2) =>
    a1.map(itm => ({
        ...a2.find((item) => (item.id === itm.id) && item),
        ...itm
    }));

console.log(mergeById(arr1, arr2));
  1. 映射到 array1
  2. 在 array2 中搜索 array1.id
  3. 如果找到它...将 array2 的结果散布到 array1

    最终数组将只包含与两个数组匹配的 id

【讨论】:

  • 伟大的!查找方法中“&& item”的目的是什么?
  • @Fabrice 我的猜测是,在写答案时,(不正确的)假设是 [].find() 要求返回找到的项目,而不仅仅是一个布尔值。但由于它现在在答案中,我们可以弥补它的一些用途 :-) 现在如果 item 是假的,它会避免匹配。所以它有点像 SQL 等三值关系代数中的 JOIN(不会在 NULL 上等值连接)。 IOW,如果 id 丢失或两边都是错误的,则没有匹配项。
  • 您在这里不需要 &amp;&amp; itemfind 将返回找到的元素。 ...a2.find(item =&gt; item.id === itm.id),
  • &amp;&amp; item不需要。如果没有项,则永远不会调用谓词回调,那为什么要有呢?
【解决方案3】:

即使合并后的数组大小不同,此解决方案也适用。 此外,即使匹配的键具有不同的名称。

使用 Map 合并两个数组,如下所示:

const arr1 = [
  { id: "abdc4051", date: "2017-01-24" }, 
  { id: "abdc4052", date: "2017-01-22" },
  { id: "abdc4053", date: "2017-01-22" }
];
const arr2 = [
  { nameId: "abdc4051", name: "ab" },
  { nameId: "abdc4052", name: "abc" }
];

const map = new Map();
arr1.forEach(item => map.set(item.id, item));
arr2.forEach(item => map.set(item.nameId, {...map.get(item.nameId), ...item}));
const mergedArr = Array.from(map.values());

console.log(JSON.stringify(mergedArr));
.as-console-wrapper { max-height: 100% !important; top: 0; }

运行stack sn-p查看结果:

[
  {
    "id": "abdc4051",
    "date": "2017-01-24",
    "nameId": "abdc4051",
    "name": "ab"
  },
  {
    "id": "abdc4052",
    "date": "2017-01-22",
    "nameId": "abdc4052",
    "name": "abc"
  },
  {
    "id": "abdc4053",
    "date": "2017-01-22"
  }
]

【讨论】:

  • 这是比接受的答案更好的答案,因为它允许不同的键和不同大小的数组
  • 这也解决了我的问题,因为我必须结合一个属性并仍然返回没有结合的对象。
  • 这是截至 2022 年 2 月的现代答案。@Adel / Op 应该真正考虑更改已接受的答案。
  • 完美,这个答案的时间复杂度为 O(n),而如果我们使用 mapfind 或其他组合,则为 O(n^2)。非常感谢,我完全忘记了使用 Map 来解决这个问题
【解决方案4】:

这是一个使用 reduce 和 Object.assign 的 O(n) 解决方案

const joinById = ( ...lists ) =>
    Object.values(
        lists.reduce(
            ( idx, list ) => {
                list.forEach( ( record ) => {
                    if( idx[ record.id ] )
                        idx[ record.id ] = Object.assign( idx[ record.id ], record)
                    else
                        idx[ record.id ] = record
                } )
                return idx
            },
            {}
        )
    )

要将此函数用于 OP 的情况,请将要加入的数组传递给 joinById(注意列表是一个剩余参数)。

let joined = joinById(list1, list2)

每个列表都缩减为单个对象,其中键是 id,值是对象。如果给定的键已经有一个值,它会在它和当前记录上调用 object.assign 。

这是通用的 O(n*m) 解决方案,其中 n 是记录数,m 是键数。这仅适用于有效的对象键。您可以将任何值转换为 base64,并在需要时使用它。

const join = ( keys, ...lists ) =>
    lists.reduce(
        ( res, list ) => {
            list.forEach( ( record ) => {
                let hasNode = keys.reduce(
                    ( idx, key ) => idx && idx[ record[ key ] ],
                    res[ 0 ].tree
                )
                if( hasNode ) {
                    const i = hasNode.i
                    Object.assign( res[ i ].value, record )
                    res[ i ].found++
                } else {
                    let node = keys.reduce( ( idx, key ) => {
                        if( idx[ record[ key ] ] )
                            return idx[ record[ key ] ]
                        else
                            idx[ record[ key ] ] = {}
                        return idx[ record[ key ] ]
                    }, res[ 0 ].tree )
                    node.i = res[ 0 ].i++
                    res[ node.i ] = {
                        found: 1,
                        value: record
                    }
                }
            } )
            return res
        },
        [ { i: 1, tree: {} } ]
         )
         .slice( 1 )
         .filter( node => node.found === lists.length )
         .map( n => n.value )

这与 joinById 方法基本相同,只是它保留了一个索引对象来标识要连接的记录。记录存储在数组中,索引存储给定键集的记录位置以及在其中找到的列表数。

每次遇到相同的键集时,它都会在树中找到节点,更新其索引处的元素,并增加找到的次数。

加入后,idx 对象从带有切片的数组中移除,并且移除每个集合中未找到的所有元素。这使其成为内部联接,您可以删除此过滤器并获得完整的外部联接。

最后,每个元素都映射到它的值,并且您拥有连接的数组。

【讨论】:

  • 这是我的首选答案。非常感谢您对提出的每个解决方案进行详细分析。
  • 对不起,这个答案对我来说是不可理解的。 - 一方面:我应该在哪里插入问题的原始海报提供的两个示例数组?
  • @Henke 很抱歉没有对此进行解释。这两个数组被传递给第一个函数。您可以复制并粘贴它,将两个数组传入并返回连接结果。我将使用 OP 的数据通过示例更新答案。
【解决方案5】:

您可以使用任意数量的数组并映射到相同索引的新对象上。

var array1 = [{ id: "abdc4051", date: "2017-01-24" }, { id: "abdc4052", date: "2017-01-22" }],
    array2 = [{ id: "abdc4051", name: "ab" }, { id: "abdc4052", name: "abc" }],
    result = [array1, array2].reduce((a, b) => a.map((c, i) => Object.assign({}, c, b[i])));
    
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

【讨论】:

  • 你能帮我理解这条线吗result = [array1, array2].reduce((a, b) =&gt; a.map((c, i) =&gt; Object.assign({}, c, b[i])));这里发生了什么?它是比较两个数组并分配获得公共键的值吗?
  • 它采用所有数组进行连接,并将分配的单个元素 a(整个数组)的结果映射到 cbb[i] 的项目。
  • 当 ID 不同或顺序不同时,此代码不起作用 var array1 = [{ id: "abdc4053", date: "2017-01-24" }, { id: "abdc4054", date: "2017-01-22" }], array2 = [{ id: "abdc4051", name: "ab" }, { id: "abdc4052", name: "abc" }], result = [array1, array2].reduce((a, b) =&gt; a.map((c, i) =&gt; Object.assign({}, c, b[i]))); console.log(result);
【解决方案6】:

如果您有 2 个数组需要根据值合并,即使它们的顺序不同

let arr1 = [
    { id:"1", value:"this", other: "that" },
    { id:"2", value:"this", other: "that" }
];

let arr2 = [
    { id:"2", key:"val2"},
    { id:"1", key:"val1"}
];

你可以这样做

const result = arr1.map(item => {
    const obj = arr2.find(o => o.id === item.id);
    return { ...item, ...obj };
  });

console.log(result);

【讨论】:

    【解决方案7】:

    要合并 id 上的两个数组,假设数组长度相等:

    arr1.map(item => ({
        ...item,
        ...arr2.find(({ id }) => id === item.id),
    }));
    

    【讨论】:

      【解决方案8】:

      我们可以在这里使用lodash。 _.merge 按预期工作。它适用于存在的公共密钥。

      _.merge(array1, array2)
      

      【讨论】:

        【解决方案9】:

        这些解决方案都不适合我的情况:

        • 缺失的对象可以存在于任一数组中
        • 运行时复杂度为 O(n)

        笔记:

        • 我使用了 lodash,但很容易用其他东西替换
        • 还使用了 Typescript(只是删除/忽略类型)
        import { keyBy, values } from 'lodash';
        
        interface IStringTMap<T> {
          [key: string]: T;
        }
        
        type IIdentified = {
          id?: string | number;
        };
        
        export function mergeArrayById<T extends IIdentified>(
          array1: T[],
          array2: T[]
        ): T[] {
          const mergedObjectMap: IStringTMap<T> = keyBy(array1, 'id');
        
          const finalArray: T[] = [];
        
          for (const object of array2) {
            if (object.id && mergedObjectMap[object.id]) {
              mergedObjectMap[object.id] = {
                ...mergedObjectMap[object.id],
                ...object,
              };
            } else {
              finalArray.push(object);
            }
          }
        
          values(mergedObjectMap).forEach(object => {
            finalArray.push(object);
          });
        
          return finalArray;
        }
        

        【讨论】:

          【解决方案10】:

          您可以使用数组方法

          let arrayA=[
          {id: "abdc4051", date: "2017-01-24"},
          {id: "abdc4052", date: "2017-01-22"}]
          
          let arrayB=[
          {id: "abdc4051", name: "ab"},
          {id: "abdc4052", name: "abc"}]
          
          let arrayC = [];
          
          
            
          
          arrayA.forEach(function(element){
            arrayC.push({
            id:element.id,
            date:element.date,
            name:(arrayB.find(e=>e.id===element.id)).name
            });  
          });
          
          console.log(arrayC);
          
          //0:{id: "abdc4051", date: "2017-01-24", name: "ab"}
          //1:{id: "abdc4052", date: "2017-01-22", name: "abc"}

          【讨论】:

          • isBiggerThan10() 函数只是一个遗留的?在这里真的没有任何意义吗?
          【解决方案11】:

          这是单行代码(数组中元素的顺序并不重要,假设存在 1 对 1 的关系):

          var newArray = array1.map(x=>Object.assign(x, array2.find(y=>y.id==x.id)))
          

          【讨论】:

          • 我发现 - 在 SQL 术语中 - 这个答案产生了左外连接,鉴于 arr1剩下数组(表)和arr2正确的大批。 (该问题的原始发帖者并未阐明他希望回答哪种类型的连接。)
          【解决方案12】:

          我遍历第一个数组并在第二个数组上使用 .find 方法找到 id 相等的匹配项并返回结果。

          const a = [{ id: "abdc4051", date: "2017-01-24" },{ id: "abdc4052", date: "2017-01-22" }];
          const b = [{ id: "abdc4051", name: "ab" },{ id: "abdc4052", name: "abc" }];
          
          console.log(a.map(itm => ({...itm, ...b.find(elm => elm.id == itm.id)})));

          【讨论】:

            【解决方案13】:

            您可以递归地将它们合并为一个,如下所示:

            function mergeRecursive(obj1, obj2) {
                for (var p in obj2) {
                    try {
                        // Property in destination object set; update its value.
                        if (obj2[p].constructor == Object) {
                            obj1[p] = this.mergeRecursive(obj1[p], obj2[p]);
            
                        } else {
                            obj1[p] = obj2[p];
            
                        }
            
                    } catch (e) {
                        obj1[p] = obj2[p];
            
                    }
                }
                return obj1;
            }
            
            arr1 = [
                { id: "abdc4051", date: "2017-01-24" },
                { id: "abdc4052", date: "2017-01-22" }
            ];
            arr2 = [
                { id: "abdc4051", name: "ab" },
                { id: "abdc4052", name: "abc" }
            ];
            
            mergeRecursive(arr1, arr2)
            console.log(JSON.stringify(arr1))

            【讨论】:

              【解决方案14】:

              无论您可以合并的顺序如何,

              function merge(array,key){
                  let map = {};
                  array.forEach(val=>{
                      if(map[val[key]]){
                          map[val[key]] = {...map[val[key]],...val};
                      }else{
                          map[val[key]] = val;
                      }
                  })
                  return Object.keys(map).map(val=>map[val]);
              }
              
              let b = [
                { id: "abdc4051", name: "ab" },
                { id: "abdc4052", name: "abc" }
              ];
              let a = [
                { id: "abdc4051", date: "2017-01-24" }, 
                { id: "abdc4052", date: "2017-01-22" }
              ];
              
              console.log(merge( [...a,...b], 'id'));

              【讨论】:

              • 好答案。然而,对我来说重要的是两个数组中对象的顺序是否会破坏任何东西,你在上面的例子中并没有真正测试过。所以我在a stack snippet of my own 中尝试了您的解决方案,结果证明您的解决方案在这方面也工作得很好。谢谢!干杯。
              【解决方案15】:

              如果两个数组都有不相交的项目,则采用一种方法。

              const firstArray = [
                { id: 1, name: "Alex", salutation: "Mr." },
                { id: 2, name: "Maria", salutation: "Ms." },
              ];
              
              const secondArray = [
                { id: 2, address: "Larch Retreat 31", postcode: "123452" },
                { id: 3, address: "Lycroft Close 12D", postcode: "123009" },
              ];
              
              const mergeArr = (arr1, arr2) => {
                const obj = {};
              
                arr1.forEach(item => {
                  obj[item.id] = item;
                });
              
                arr2.forEach(item => {
                  obj[item.id]
                    ? (obj[item.id] = { ...obj[item.id], ...item })
                    : (obj[item.id] = item);
                });
              
                return Object.values(obj);
              };
              
              const output = mergeArr(firstArray, secondArray);
              
              console.log(output);

              【讨论】:

                【解决方案16】:

                Python 3 解决方案,适用于登陆此页面并希望找到一个的人

                def merge(studentDetails, studentMark, merge_key):
                    student_details = {}
                    student_marks = {}
                    for sd, sm in zip(studentDetails, studentMark):
                        key = sd.pop(merge_key)
                        student_details[key] = sd
                
                        key = sm.pop(merge_key)
                        student_marks[key] = sm
                
                    res = []
                    for id, val in student_details.items():
                        # Merge three dictionary together
                        temp = {**{"studentId": id}, **val, **student_marks[id]}
                        res.append(temp)
                    return res
                
                
                if __name__ == '__main__':
                    # Test Case 1
                    studentDetails = [
                        {"studentId": 1, "studentName": 'Sathish', "gender": 'Male', "age": 15},
                        {"studentId": 2, "studentName": 'kumar', "gender": 'Male', "age": 16},
                        {"studentId": 3, "studentName": 'Roja', "gender": 'Female', "age": 15},
                        {"studentId": 4, "studentName": 'Nayanthara', "gender": 'Female', "age": 16},
                    ]
                    studentMark = [
                        {"studentId": 1, "mark1": 80, "mark2": 90, "mark3": 100},
                        {"studentId": 2, "mark1": 80, "mark2": 90, "mark3": 100},
                        {"studentId": 3, "mark1": 80, "mark2": 90, "mark3": 100},
                        {"studentId": 4, "mark1": 80, "mark2": 90, "mark3": 100},
                    ]
                
                    # Test Case 2
                    array1 = [
                        {"id": "abdc4051", "date": "2017-01-24"},
                        {"id": "abdc4052", "date": "2017-01-22"}
                    ]
                    array2 = [
                        {"id": "abdc4051", "name": "ab"},
                        {"id": "abdc4052", "name": "abc"}
                    ]
                
                    output = merge(studentDetails, studentMark, merge_key="studentId")
                    [print(a) for a in output]
                
                    output = merge(array1, array2, merge_key="id")
                    [print(a) for a in output]
                

                输出

                {'studentId': 1, 'studentName': 'Sathish', 'gender': 'Male', 'age': 15, 'mark1': 80, 'mark2': 90, 'mark3': 100}
                {'studentId': 2, 'studentName': 'kumar', 'gender': 'Male', 'age': 16, 'mark1': 80, 'mark2': 90, 'mark3': 100}
                {'studentId': 3, 'studentName': 'Roja', 'gender': 'Female', 'age': 15, 'mark1': 80, 'mark2': 90, 'mark3': 100}
                {'studentId': 4, 'studentName': 'Nayanthara', 'gender': 'Female', 'age': 16, 'mark1': 80, 'mark2': 90, 'mark3': 100}
                {'studentId': 'abdc4051', 'date': '2017-01-24', 'name': 'ab'}
                {'studentId': 'abdc4052', 'date': '2017-01-22', 'name': 'abc'}
                

                【讨论】:

                  【解决方案17】:

                  好吧......假设两个数组的长度相同,我可能会做这样的事情:

                  var newArr = []
                  for (var i = 0; i < array1.length; i++ {
                      if (array1[i].id === array2[i].id) {
                        newArr.push({id: array1[i].id, date: array1[i].date, name: array2[i].name});
                    }
                  }
                  

                  【讨论】:

                  • 抱歉,我错过了您帖子的最后一行。 x_X
                  【解决方案18】:

                  我能够通过两个数组的嵌套映射并更新初始数组来实现这一点:

                  member.map(mem => {
                  return memberInfo.map(info => {
                      if (info.id === mem.userId) {
                          mem.date = info.date;
                          return mem;
                          }
                      }
                  }
                  

                  【讨论】:

                    【解决方案19】:

                    有很多解决方案可用于此,但是,我们可以简单地使用for循环和if条件来获取合并数组。

                    const firstArray = [
                      { id: 1, name: "Alex", salutation: "Mr." },
                      { id: 2, name: "Maria", salutation: "Ms." },
                    ];
                    
                    const secondArray = [
                      { id: 1, address: "Larch Retreat 31", postcode: "123452" },
                      { id: 2, address: "Lycroft Close 12D", postcode: "123009" },
                    ];
                    
                    let mergedArray: any = [];
                    
                    for (const arr1 of firstArray) {
                      for (arr2 doc of secondArray) {
                        if (arr1.id === arr2.id) {
                          mergedArray.push({ ...arr1, ...arr2 });
                        }
                      }
                    }
                    
                    console.log(mergedArray)
                    

                    【讨论】:

                    • 我担心这段代码的复杂性,因为它是 O^(n*m) 并且对于大数据量效率不高
                    【解决方案20】:

                    这是将最佳答案 (jsbisht) 转换为接受键作为参数的函数。

                    const mergeArraysByKeyMatch = (array1, array2, key1, key2) => {
                      const map = new Map();
                      array1.forEach((item) => map.set(item[key1], item));
                      array2.forEach((item) =>
                        map.set(item[key2], { ...map.get(item[key2]), ...item })
                      );
                      const merged = Array.from(map.values());
                    
                      return merged;
                    };
                    

                    【讨论】:

                      【解决方案21】:

                      Typescript O(n+m)(可以归类为 O(n))解决方案;没有lodash:

                      // RequireAtLeastOne from https://stackoverflow.com/questions/40510611/typescript-interface-require-one-of-two-properties-to-exist/49725198#49725198
                      type RequireAtLeastOne<T, Keys extends keyof T = keyof T> = Pick<
                        T,
                        Exclude<keyof T, Keys>
                      > &
                        {
                          [K in Keys]-?: Required<Pick<T, K>> & Partial<Pick<T, Exclude<Keys, K>>>;
                        }[Keys];
                      
                      export const mergeDualArraysOnKey = <
                        K extends PropertyKey,
                        T extends RequireAtLeastOne<{ [f in PropertyKey]?: unknown }, K>
                      >(
                        key: K,
                        ...lists: [T[], T[]]
                      ): T[] => {
                        const lookup: { [key in string]: number } = {};
                        return lists[0].concat(lists[1]).reduce((acc: T[], value: T, i: number) => {
                          const lookupKey = `${value[key]}`;
                          if (lookup.hasOwnProperty(lookupKey)) {
                            acc[lookup[lookupKey]] = Object.assign({}, acc[lookup[lookupKey]], value);
                          } else {
                            acc.push(value);
                            lookup[lookupKey] = acc.length - 1;
                          }
                          return acc;
                        }, []);
                      };
                      

                      首先连接两个数组,然后遍历新创建的数组。它使用查找表(对象)将项目的索引存储在具有相同键的最终合并数组中,并就地合并对象。

                      如果这需要扩展以处理更多数组,可以使用循环或递归作为包装函数:

                      const mergeArrays = <
                        K extends PropertyKey,
                        T extends RequireAtLeastOne<{ [f in PropertyKey]?: unknown }, K>
                      >(
                        key: K,
                        ...lists: T[][]
                      ): T[] => {
                        if (lists.length === 1) {
                          return lists[0];
                        }
                        const l1 = lists.pop() || [];
                        const l2 = lists.pop() || [];
                        return mergeArrays(key, mergeDualArraysOnKey(key, l1, l2), ...lists);
                      };
                      

                      用法是:

                      const arr1 = [
                        { id: "abdc4052", date: "2017-01-22" },
                        { id: "abdc4052", location: "US" },
                        { id: "abdc4051", date: "2017-01-24" },
                        { id: "abdc4053", date: "2017-01-24" },
                        { id: "abdc4054", date: "2017-01-24" },
                        { id: "abdc4055", location: "US" },
                      ];
                      
                      const arr2 = [
                        { id: "abdc4052", date: "2017-01-22" },
                        { id: "abdc4052", name: "abc" },
                        { id: "abdc4055", date: "2017-01-24" },
                        { id: "abdc4055", date: "2017-01-24", name: "abcd" },
                      ];
                      
                      const arr3 = [{ id: "abdc4056", location: "US" }];
                      
                      const arr4 = [
                        { id: "abdc4056", name: "abcde" },
                        { id: "abdc4051", name: "ab--ab" },
                      ];
                      
                      mergeArrays<
                          "id",
                          {
                            id: string;
                            date?: string;
                            location?: string;
                            name?: string;
                          }
                        >("id", arr1, arr2, arr3, arr4)
                      

                      【讨论】:

                        【解决方案22】:

                        根据您的示例,您可以这样做:

                        const arrayOne = [
                          { id: "abdc4051", date: "2017-01-24" }, 
                          { id: "abdc4052", date: "2017-01-22" }
                        ]
                        
                        const arrayTwo = [
                          { id: "abdc4051", name: "ab" },
                          { id: "abdc4052", name: "abc" }
                        ]
                        
                        const mergeArrays = () => {
                          arrayOne.forEach((item, i) => {
                            const matchedFound = arrayTwo.findIndex(a => a.id === item.id);
                            arrayOne[i] = {
                              ...item,
                              ...matchedFound,
                            }
                          });
                        };
                        
                        mergeArrays();
                        
                        console.log(arrayOne);
                        

                        【讨论】:

                          【解决方案23】:

                          这是一个版本,当你有一个对象和一个数组,你想合并它们并给数组一个键值,以便它很好地适合对象。

                          var fileData = [
                              { "id" : "1", "filename" : "myfile1", "score" : 33.1 }, 
                              { "id" : "2", "filename" : "myfile2", "score" : 31.4 }, 
                              { "id" : "3", "filename" : "myfile3", "score" : 36.3 }, 
                              { "id" : "4", "filename" : "myfile4", "score" : 23.9 }
                          ];
                          
                          var fileQuality = [0.23456543,0.13413131,0.1941344,0.7854522];
                          
                          var newOjbect = fileData.map((item, i) => Object.assign({}, item, {fileQuality:fileQuality[i]}));
                          
                          console.log(newOjbect);

                          【讨论】:

                            猜你喜欢
                            • 1970-01-01
                            • 1970-01-01
                            • 1970-01-01
                            • 1970-01-01
                            • 1970-01-01
                            • 1970-01-01
                            • 2021-09-12
                            • 2022-07-21
                            相关资源
                            最近更新 更多