简体   繁体   English

如何合并两个不同大小的对象数组?

[英]How do you merge two different arrays of objects of the same size?

I'm attempting to merge the following two objects into one.我试图将以下两个对象合并为一个。 I want it to be an array of objects with values {companyType, companyName, companyLocation, companyPhone, score} but everything I've tried doesn't merge the objects properly.我希望它是一个具有值 {companyType, companyName, companyLocation, companyPhone, score} 的对象数组,但我尝试过的一切都没有正确合并对象。 The actual objects are much larger but they are the same exact size.实际对象要大得多,但它们的确切大小相同。 So I need something that deals with many objects in an array not just two items per array.所以我需要一些东西来处理数组中的许多对象,而不仅仅是每个数组的两个项目。

let company_details = [{companyType: 'Carrier',
                        companyName: 'Auto',
                        companyLocation: 'San Diego, CA',
                        companyPhone: '(123) 456-7890' },
                       {companyType: 'Dealer',
                        companyName: 'Car',
                        companyLocation: 'Indianapolis, IN',
                        companyPhone: '(234) 567-8901' }]

let scoreArr= [{score: 'Your Rating: None'},
               {score: 'Your Rating: Positive'}]

This approach takes an array of same length arrays and merge the objects at every index.这种方法采用相同长度数组的数组并在每个索引处合并对象。

Methods used:使用的方法:

  • Array#reduce for reducing a set of arrays and getting a single array. Array#reduce用于减少一组数组并获得单个数组。

  • Array#map for mapping objects with an object from the left side of reduce a and an object from the right side of reduce b at the same index. Array#map用于将对象与来自reduce a左侧的对象和来自reduce b右侧的对象映射到相同的索引处。

  • spread syntax ... for cloning an object as object literal. 传播语法...用于将对象克隆为对象文字。 The order defines the value of same named properties, the last winns.该顺序定义了同名属性的值,最后一个获胜。

The result is an array of objects.结果是一个对象数组。

 let companies = [{ companyType: 'Carrier', companyName: 'Auto', companyLocation: 'San Diego, CA', companyPhone: '(123) 456-7890' }, { companyType: 'Dealer', companyName: 'Car', companyLocation: 'Indianapolis, IN', companyPhone: '(234) 567-8901' }], scores = [{ score: 'Your Rating: None' }, { score: 'Your Rating: Positive' }], merged = [companies, scores].reduce((a, b) => a.map((o, i) => ({ ...o, ...b[i] }))); console.log(merged);
 .as-console-wrapper { max-height: 100% !important; top: 0; }

Some functional languages have very good list comprehension tools, for instance Haskell's zipWith.一些函数式语言有非常好的列表理解工具,例如 Haskell 的 zipWith。 It takes two lists and applies a bivariate function to each set of elements.它需要两个列表并对每组元素应用一个二元函数。

However, we can easily implement it with arrow functions in present JS (ES6):但是,我们可以在现有的 JS (ES6) 中使用箭头函数轻松实现它:

const zipWith = f => xs => ys => xs.map((x, i) => f(x, ys[i]));

In case you are not used to arrow function syntax: zipWith is a function with three parameters, a function f , and arrays xs and ys .如果您不习惯箭头函数语法: zipWith是一个具有三个参数的函数,一个函数f以及数组xsys

We use then map , a built in method of Array.我们使用 then map ,一个内置的 Array 方法。 It takes a function as argument and applies each element of xs to it.它接受一个函数作为参数并将xs 的每个元素应用于它。 Hence the second arrow function in the argument of map.因此,map 参数中的第二个箭头函数。 When map receives a bivariate function, it provides the array index corresponding to each element as second argument, here i .map接收到一个二元函数时,它提供每个元素对应的数组索引作为第二个参数,这里是i

We provide now x an element of xs as first argument to our provided function f .我们现在提供x一个xs的元素作为我们提供的函数f 的第一个参数。 The second argument is the corresponding element of the other array ys[i] .第二个参数是另一个数组ys[i]的对应元素。

With the zipWith function we need another function to merge those objects in your array.使用zipWith函数,我们需要另一个函数来合并数组中的这些对象。 The Object.assign method helps here: Object.assign方法在这里有帮助:

const mergerFun = (a, b) => Object.assign({}, a, b)

Now apply it to your arrays:现在将其应用于您的数组:

const result = zipWith(mergerFun)(company_details)(scoreArr);

Here is it all in a snippet you can run.这是您可以运行的代码片段中的全部内容。 I've trimmed your objects to make the snippet a bit clearer.我已经修剪了你的对象,使代码片段更清晰一些。

 const companyDetails = [ { type: 'Carrier', name: 'Auto', }, { type: 'Dealer', name: 'Car', }, ]; const scoreArr = [ { score: 'None' }, { score: 'Positive' }, ]; // zipWith :: ( a -> b -> c ) -> [a] -> [b] -> [c] const zipWith = f => xs => ys => xs.map((x, i) => f(x, ys[i])); // mergerFun :: a -> b -> c const mergerFun = (a, b) => Object.assign({}, a, b); // put it all together const result = zipWith(mergerFun)(companyDetails)(scoreArr); console.log(result);

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

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