简体   繁体   English

通过值为数组的键组合两个对象

[英]Combining two objects by keys whose values are arrays

I have two javascript objects like below 我有两个如下的JavaScript对象

first =  {b : ["A" , "B"] , c : ["C" , "D"] , d : ["Z"]}
second = {b : ["E" , "F"] , c : ["X"]}

I want result like this 我想要这样的结果

result = {b : ["A" , "B" , "E" , "F"] , c : ["C" , "D" ,"X"] , d :["Z"]}

I was playing around npm lodash but could not find a way to do it. 我在npm lodash附近玩耍,但找不到办法。 Can some body help. 可以帮助身体。 I am new to Javascript world. 我是Java语言世界的新手。

You could use mergeWith() and add custom function to concat arrays as customizer argument. 您可以使用mergeWith()并将自定义函数添加到concat数组作为customizer参数。

 var first = {b : ["A" , "B"] , c : ["C" , "D"] , d : ["Z"]} var second = {b : ["E" , "F"] , c : ["X"]} var result = _.mergeWith(first, second, function(a, b) { return [].concat(a, b) }) console.log(JSON.stringify(result)) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script> 

This will help you. 这将为您提供帮助。

 var first = {b : ["A" , "B"] , c : ["C" , "D"] , d : ["Z"]}; var second = {b : ["E" , "F"] , c : ["X"]}; var newObj = {}; for(let i in first) { if(second.hasOwnProperty(i)) { var tempArray = first[i]; for(let j in second[i]) { tempArray.push(second[i][j]); } newObj[i] = tempArray; } else { newObj[i] = first[i]; } } console.log(JSON.stringify(newObj)); 

var first = {b : ["A" , "B"] , c : ["C" , "D"] , d : ["Z"]};
var second = {b : ["E" , "F"] , c : ["X"]};
// merge expects an array of objects to be used as its parameter
var merge = function merge( objs ) {
    var result = {};
    // for each object sent to this function.
    objs.forEach(function( obj ) {
        // Grab the array containing all the property keys.
        var keys = Object.keys(obj);
        // Loop over each keyname
        keys.forEach(function( keyName ) {
            // first, check if the key exists in our result. If not, create it and assign it an array.
            if (!result.hasOwnProperty(keyName)) result[keyName] = [];
            // Merge the array inside the object into the result by concatenation.
            result[keyName] = result[keyName].concat(obj[keyName]);
        });
    });
    return result;
};
// Use the function
var result = merge([ first, second ]);
console.log(JSON.stringify(result));
// The caveat here is that all the letters in the array are just added, we don't check for duplicates atm
// If duplicates are a thing, just change the .concat into another loop that checks if a letter is already in the array or not.

The lodash mergeWith docs use this exact thing as an example: lodash mergeWith文档使用此确切示例作为示例:

 function customizer(objValue, srcValue) { // if merging 2 arrays, concat them together if (_.isArray(objValue)) { return objValue.concat(srcValue); } } var first = {b : ["A" , "B"] , c : ["C" , "D"] , d : ["Z"]}, second = {b : ["E" , "F"] , c : ["X"]} console.log(_.mergeWith(first, second, customizer)); 
 <script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.js"></script> 

With no third party library needed (lodash or else) and a nice functional style, you can do it like this 无需第三方库(用破折号或其他符号)和良好的功能样式,就可以像这样

 let first = {b : ["A" , "B"] , c : ["C" , "D"] , d : ["Z"]} let second = {b : ["E" , "F"] , c : ["X"]} let sources = [first, second]; let unique = (...sources) => Array.from(new Set([].concat(...sources))); let join = (...sources) => key => [].concat(...sources.map(source => source[key] || [])); let keys = unique(...sources.map(source => Object.keys(source))); let merged = keys.reduce((map, key) => (map[key] = join(first, second)(key)) && map, {}); console.log(merged); 

this will handle any number of dictionaries as a source and merge all of them together. 这会将任何数量的词典作为源,并将它们全部合并在一起。

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

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