Home > Blockchain >  Combine Object/Array using Vanilla JS
Combine Object/Array using Vanilla JS

Time:11-09

How do you combine two objects like this?

const target = { year1 : {}, year2: {somevalue2...}};
const source = { year1 : {somevalue1...}, year2: {} };

expected Input:

{ year1 : {somevalue1}, year2 : {somevalue2} }

Thank you!

CodePudding user response:

Use lodash _.merge

const target = { year1 : {}, year2: {s:1}}
const source = { year1 : {s:2}, year2: {} }
const result = _.merge(target, source);
console.log('result', result)
// => { year1 : {s:2}, year2: {s:1}}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>

CodePudding user response:

You can use nested Array#reduce a way to look at {} as null as in the following demo:

const target = { year1 : {}, year2: {somekey2:"somevalue2"}};
const source = { year1 : {somekey1:"somevalue1"}, year2: {} };

//A function to convert any {} to null
const e2Null = obj => 
  obj && 
  Object.keys(obj).length === 0 && 
  obj.constructor === Object ? 
  null : obj;

const output = [source,target]
    .reduce((acc,cur) => Object.keys(cur)
        .reduce((a,c) => ({...a,[c]:acc[c] ?? e2Null(cur[c])}), {}),{}
    );

console.log( output );

Alternatively, you can use jQuery's .isEmptyObject(...) method as follows:

const target = { year1 : {}, year2: {somekey2:"somevalue2"}};
const source = { year1 : {somekey1:"somevalue1"}, year2: {} };

const e2Null = obj => jQuery.isEmptyObject(obj) ? null : obj

const output = [source,target]
    .reduce((acc,cur) => Object.keys(cur)
        .reduce((a,c) => ({...a,[c]:acc[c] ?? e2Null(cur[c])}), {}),{}
    );
    
console.log( output );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

CodePudding user response:

You can recursively iterate over all the properties of target and source using Object.entries() or Object.keys(), and copy the properties that you want to the source or to a new object.

Something like that:

const combine = (target, source) => {
  for(const [key, value] of Object.entries(source)) {
    // here you copy the `value` to `target[key]` or
    // if the value is an object you can call `combine()` recursively
    // on the `value` and `target[key]`
  }
}
  • Related