1

I am trying to merge the objects recursively.

what I have

arrayOfObjects = [{a1:{aa:k1}},{a1:{ab:k2}},{a1:{ac:k3}},{a1:{aa:k4}},{a1:{ab:k5}}]; 

what I need is

{a1:{aa:k1,ab:k2,ac:k3,aa:k4,ab:k5}} 

I made a function

function merg(array){ value = {}; if(array.length>0){ $.each(array, function (i) { value = $.extend(true,{},value,array[i]); }); } return value; }; console.log(merg(arrayOfObjects)); 

what I get is

{a1:{aa:k1,ab:k2,ac:k3}} 

aa:k4,ab:k5 are missing(may due to same key value )

if the deep merge is false I get only one value

value = $.extend({},value,array[i]); {a1:{aa:k1}} 
1
  • 1
    You can't have duplicate keys in an object. Objects are maps whose keys are unique. You could merge duplicate keys into arrays, but not duplicates keys twice. It's senseless, ask yourself how do you expect to access a1.aa. Which value do you expect to get, is it k1 or k4? How do you differ them? Commented Jun 7, 2019 at 15:12

1 Answer 1

1

We can make use of Symbols,

var arr = [{a1:{aa:'k1'}},{a1:{ab:'k2'}},{a1:{ac:'k3'}},{a1:{aa:'k4'}},{a1:{ab:'k5'}}];; var op = {}; var result = {}; var globalKey; arr.forEach((ar) => { var [key, value] = Object.entries(ar)[0]; globalKey = key; var [innerKey, innerValue] = Object.entries(value)[0]; op[Symbol(innerKey)] = innerValue; }); result[globalKey] = op; console.log(result);

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.