简体   繁体   English

Javascript:在多个对象+别名数组中匹配对象

[英]Javascript: Matching Objects in Multiple Arrays of Objects + Aliases

I want to match multiple arrays and build another array whenever there is match. 我想匹配多个数组,并在存在匹配项时构建另一个数组。 The key could match in any number of arrays or none at all. 键可以匹配任意数量的数组,也可以完全不匹配。

[ [{ 'a': 13 }, { 'b': 62 }, { 'c': 93 }, { 'd': 52 }],
  [{ 's': 15 }, { 'y': 15 }, { 'x': 78 }, { 'd': 84 }],
  [{ 't': 35 }, { 'd': 33 }, { 'x': 12 }, { 'c': 62 }] ]

Desired result: 所需结果:

[ {label: c,  arr1: 93,    arr2: null,  arr3: 63},
  {label: d,  arr1: 52,    arr2: 84,    arr3: 33},
  {label: x,  arr1: null,  arr2: 78,    arr3: 12} ]

.

label   arr1    arr2    arr3
============================
c       93      null    62
d       52      84      33
x       null    78      12

A more advanced question to go along with that. 还有一个更高级的问题。 Is it possible to alias some keys. 是否可以对某些键进行别名。 Eg. 例如。 perhaps 'b' is also known as 'y', and 's' as 't'. 也许“ b”也被称为“ y”,而“ s”也被称为“ t”。

Try something like this: 尝试这样的事情:

let output = [];
let aliases = {'b': ['y'], 's': ['t']};
let totalArrays = yourArray.length;

yourArray.forEach((innerArray, i) => 
   innerArray.forEach(obj =>{
      for(var key in obj){
         let current = output.find(e => e.label == key || (aliases[e.label] || []).indexOf(key) !== -1);
            if(!current){
               current = { label: key };
               for(let i = 0; i < totalArrays; i++){
                   current['arr' + (i + 1)] = null;
               }
               output.push(current);
           }

           current['arr'+ (i +1)] = obj[key];
       } 
 }));

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

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