Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge two nested objects in javascript

Tags:

javascript

I tried to merge using this way but it making two different keys of meta_information and meta_information.image

merchant = Object.assign(merchant, media_mode)

I have tried this way but its not working

var media_mode = {
    "featured_media_square" : "square",
    "featured_media_landscape" :"landscape",
    "logo" : "a.png",
    "meta_information.image" : "b.png"  
}

var merchant = {meta_information : {image : ""}}

I want to get result like this

merchant = {
    "featured_media_square" : "square",
     "featured_media_landscape" : "landscape",
     "logo" : "a.png",
     "meta_information" : {"image" : "b.png"}  
}
like image 222
Sahil Avatar asked Feb 11 '26 20:02

Sahil


2 Answers

var media_mode = {
  "featured_media_square" : "square",
  "featured_media_landscape":"landscape",
  "logo":"a.png",
  "meta_information.image":"b.png"  
}

var merchant = {meta_information:{image:""}};
  
for (var key in media_mode) {
  	  var kn = key.split(".");
  	  for (var key2 in merchant) {
    if (kn[0] === key2) {
    	var tmp = media_mode[key];
        media_mode[kn[0]] = {};
    	media_mode[kn[0]][kn[1]] = tmp;
        delete media_mode[key]
    }
  }
}
  
console.log(media_mode);
ECMA5 version.
like image 114
Κωλζαρ Avatar answered Feb 13 '26 08:02

Κωλζαρ


They cant merge, you would have to remap them manually, for instance desctructure media_mode, and pull "image" out of it and then having rest of the object as "...rest", then just put that together in the exact model you asked for

var media_mode = {
  featured_media_square: "square",
  featured_media_landscape: "landscape",
  logo: "a.png",
  "meta_information.image": "b.png",
};

var { "meta_information.image": image, ...rest } = media_mode;

merchant = {
  ...rest,
  meta_information: { image },
};

console.log(merchant);

ES5 as requested

var media_mode = {
  featured_media_square: "square",
  featured_media_landscape: "landscape",
  logo: "a.png",
  "meta_information.image": "b.png",
};

const image = media_mode["meta_information.image"];

var merchant = Object.assign({}, media_mode, {
  meta_information: { image: image },
});

console.log(merchant);

note that in this solution key "meta_information.image" remains in the result, if you would insists on removing it, just run

delete merchant["meta_information.image"]
like image 33
Lukáš Gibo Vaic Avatar answered Feb 13 '26 09:02

Lukáš Gibo Vaic