How to Merge Two JavaScript Objects Together in Es6+

Merge two objects with ES6

You can use Object.assign() to merge them into a new object:

const response = {  lat: -51.3303,  lng: 0.39440}
const item = { id: 'qwenhee-9763ae-lenfya', address: '14-22 Elder St, London, E1 6BT, UK'}
const newItem = Object.assign({}, item, { location: response });
console.log(newItem );

How do I merge two javascript objects together in ES6+?

You will be able to do a shallow merge/extend/assign in ES6 by using Object.assign:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

Syntax:

Object.assign(target, sources);

where ...sources represents the source object(s).

Example:

var obj1 = {name: 'Daisy', age: 30};
var obj2 = {name: 'Casey'};

Object.assign(obj1, obj2);

console.log(obj1.name === 'Casey' && obj1.age === 30);
// true

Es6 merge two objects using spread not working

arr3 is overwriting the values from arr2 because both objects share the same keys. Assuming arr2 and arr3's keys are identical, you can use the following solution:


var arr2 = {  "20080": {    "ProductQuantitesId": 20080,        "CustomerPrice": 100,    "DisplayQuantity": "20 L",       "DisplayProductName": "Bisleri Mineral Water",    "DiscountedPrice": 20,    "DiscountedPercentage": 17  },  "20110": {    "ProductQuantitesId": 20110,       "CustomerPrice": 270,    "DisplayQuantity": "5 kgs",        "DisplayProductName": "Srujana Curd Bucket",    "DiscountedPrice": 30,    "DiscountedPercentage": 10  } }
var arr3 = { "20080": { "Qty": 2, }, "20110": { "Qty": 3, } }
// First, get the keys from arr2 using Object.keys().// Then, use Array.prototype.reduce() to iterate through the keys.// In the callback, acc is referring to the empty object, {}, // passed as the second argument in reduce().const result = Object.keys(arr2).reduce((acc, key) => {
// Set the value of the resulting object's key equal to the // combined key-values of arr2 and arr3 acc[key] = { ...arr2[key], ...arr3[key] } // Make sure to return the object return acc}, {})
console.log(result)

How can I merge properties of two JavaScript objects dynamically?

ECMAScript 2018 Standard Method

You would use object spread:

let merged = {...obj1, ...obj2};

merged is now the union of obj1 and obj2. Properties in obj2 will overwrite those in obj1.

/** There's no limit to the number of objects you can merge.
* Later properties overwrite earlier properties with the same name. */
const allRules = {...obj1, ...obj2, ...obj3};

Here is also the MDN documentation for this syntax. If you're using babel you'll need the @babel/plugin-proposal-object-rest-spread plugin for it to work (This plugin is included in @babel/preset-env, in ES2018).

ECMAScript 2015 (ES6) Standard Method

/* For the case in question, you would do: */
Object.assign(obj1, obj2);

/** There's no limit to the number of objects you can merge.
* All objects get merged into the first object.
* Only the object in the first argument is mutated and returned.
* Later properties overwrite earlier properties with the same name. */
const allRules = Object.assign({}, obj1, obj2, obj3, etc);

(see MDN JavaScript Reference)


Method for ES5 and Earlier

for (var attrname in obj2) { obj1[attrname] = obj2[attrname]; }

Note that this will simply add all attributes of obj2 to obj1 which might not be what you want if you still want to use the unmodified obj1.

If you're using a framework that craps all over your prototypes then you have to get fancier with checks like hasOwnProperty, but that code will work for 99% of cases.

Example function:

/**
* Overwrites obj1's values with obj2's and adds obj2's if non existent in obj1
* @param obj1
* @param obj2
* @returns obj3 a new object based on obj1 and obj2
*/
function merge_options(obj1,obj2){
var obj3 = {};
for (var attrname in obj1) { obj3[attrname] = obj1[attrname]; }
for (var attrname in obj2) { obj3[attrname] = obj2[attrname]; }
return obj3;
}

Js ES6, Merge 2 objects and store in array instead replacing existent key

You can do this:

let result = { ...user, ...otherInfo, phone: user.phone && otherInfo.phone ? [user.phone, otherInfo.phone]: user.phone || otherInfo.phone };

es6 merge two array with objects and accumulate data

You can use a Set to get just the unique ids, then you can map over that, finding the matching data and building the object in the required format:

const admin = [{    "categoryId": 66,    "categoryName": "category 66",    "id": 204  },  {    "categoryId": 149,    "teamName": "category 149",    "id": 178  }]
const member = [{ "categoryId": 66, "teamName": "category 66", "id": 271 }, { "categoryId": 68, "teamName": "category 68", "id": 264 }]
const findCategory = (categories, category) => categories .find(x => x.categoryId === category) || null;
const mergeCategories = (adminIn, memberIn) => { const mergedCategories = [ ...adminIn, ...memberIn, ]; // we would like to know just the unique id's const categoryIds = [...new Set(mergedCategories.map(x => x.categoryId))]; // we can map each unique id return categoryIds.map(categoryId => { // then we can find whether it has a matching category for each const adminCategory = findCategory(admin, categoryId); const memberCategory = findCategory(member, categoryId); // now we can use that data to build the object in the required format return { categoryId, categoryName: `category ${categoryId}`, adminId: adminCategory === null ? adminCategory : adminCategory.id, memberId: memberCategory === null ? memberCategory : memberCategory.id } });
}
const result = mergeCategories( admin, member,)
console.dir(result)

ES6 spread to merge objects in an array

You could spread the elements into an Object.assign, without further looping.

let arr = [{ a: 1, b: true }, { c: "val", d: null }],    result = Object.assign({}, ...arr);
console.log(result);

merge objects into one and override the existing object - javascript es6

You can use multiple spreads to add the property uri to product_name:

const productFields = {"category_id":{"key":"category_id","label":"Category","uri":"/products/category","value":"","items":[]},"product_name":{"key":"product_name","label":"Product Name","value":"","items":[]}};
const paramsId = 'paramsId';
const categoryId = 'categoryId';

const newProductFields = {
...productFields, // spread the base object
product_name: { // override product_name
...productFields.product_name, // add the original product_name
uri: `/products/${paramsId}/category/${categoryId}` // add the property
}
};

console.log(newProductFields);


Related Topics



Leave a reply



Submit