두 자바 스크립트 객체의 속성을 동적으로 병합하려면 어떻게해야합니까?
질문
런타임에 두 개의 (매우 간단한) JavaScript 객체를 병합 할 수 있어야합니다.예를 들어 다음을 원합니다.
var obj1 = { food: 'pizza', car: 'ford' }
var obj2 = { animal: 'dog' }
obj1.merge(obj2);
//obj1 now has three properties: food, car, and animal
이 일을 할 수있는 지어 졌습니까?나는 재귀가 필요하지 않으며, 기능을 병합 할 필요가 없으며 평면 객체의 메소드 만합니다.
답변
ECMAScript 2018 표준 방법
객체 스프레드를 사용합니다.
let merged = {...obj1, ...obj2};
병합은 이제 OBJ1과 OBJ2의 조합입니다.OBJ2의 속성은 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};
이 구문에 대한 MDN 설명서가 있습니다.바벨을 사용하는 경우 Babel-Plugin-Transform-Object-REST-Spread 플러그인이 작동해야합니다.
ECMAScript 2015 (ES6) 표준 방법
/* 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);
(MDN JavaScript 참조 참조)
ES5 및 이전의 방법
for (var attrname in obj2) { obj1[attrname] = obj2[attrname]; }
이렇게하면 OBJ2의 모든 속성을 OBJ1에 추가 할 수 있으므로 수정되지 않은 OBJ1을 사용하고자하는 경우 원하는 것이 아닐 수도 있습니다.
프로토 타입을 통해 모든 것을 쓰레기통을 사용하는 프레임 워크를 사용하는 경우 HasownProperty와 같은 수표와 함께 Facerier를 얻어야하지만 해당 코드는 99 %의 경우 작동합니다.
예제 기능 :
/**
* 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;
}
답변
jQuery에는 http://api.jquery.com/jquery.extend/에 대한 유용성이 있습니다.
jQuery 설명서에서 가져온 것 :
// Merge options object into settings object
var settings = { validate: false, limit: 5, name: "foo" };
var options = { validate: true, name: "bar" };
jQuery.extend(settings, options);
// Now the content of settings object is the following:
// { validate: true, limit: 5, name: "bar" }
위의 코드는 설정 명라는 기존 객체를 돌립니다.
두 인수를 수정하지 않고 새 객체를 만들려면 다음을 사용하십시오.
var defaults = { validate: false, limit: 5, name: "foo" };
var options = { validate: true, name: "bar" };
/* Merge defaults and options, without modifying defaults */
var settings = $.extend({}, defaults, options);
// The content of settings variable is now the following:
// {validate: true, limit: 5, name: "bar"}
// The 'defaults' and 'options' variables remained the same.
답변
하모니 ECMAScript 2015 (ES6)는이 작업을 수행 할 object.assign을 지정합니다.
Object.assign(obj1, obj2);
현재 브라우저 지원이 나아 지지만 지원이없는 브라우저를 개발하는 경우 폴리 필ill을 사용할 수 있습니다.
답변
나는 객체 속성을 병합하고 여기에서 끝내려면 코드를 위해 Googled했습니다.그러나 재귀 합병을위한 코드가 없으므로 나는 그것을 썼다.(어쩌면 jQuery 확장은 재귀 적 Btw입니까?) 어쨌든 다른 누군가가 다른 사람이 유용 할 것입니다.
(이제 코드는 object.prototype을 사용하지 않습니다. :)
암호
/*
* Recursively merge properties of two objects
*/
function MergeRecursive(obj1, obj2) {
for (var p in obj2) {
try {
// Property in destination object set; update its value.
if ( obj2[p].constructor==Object ) {
obj1[p] = MergeRecursive(obj1[p], obj2[p]);
} else {
obj1[p] = obj2[p];
}
} catch(e) {
// Property in destination object not set; create it and set its value.
obj1[p] = obj2[p];
}
}
return obj1;
}
예제
o1 = { a : 1,
b : 2,
c : {
ca : 1,
cb : 2,
cc : {
cca : 100,
ccb : 200 } } };
o2 = { a : 10,
c : {
ca : 10,
cb : 20,
cc : {
cca : 101,
ccb : 202 } } };
o3 = MergeRecursive(o1, o2);
o3처럼 객체를 생산합니다
o3 = { a : 10,
b : 2,
c : {
ca : 10,
cb : 20,
cc : {
cca : 101,
ccb : 202 } } };
답변
Underscore.js의 Extend-메서드는이 옵션을 한 라이너에서 수행합니다.
_.extend({name : 'moe'}, {age : 50});
=> {name : 'moe', age : 50}
답변
jQuery Extend ()와 유사하게 Angularjs와 동일한 기능이 있습니다.
// Merge the 'options' object into the 'settings' object
var settings = {validate: false, limit: 5, name: "foo"};
var options = {validate: true, name: "bar"};
angular.extend(settings, options);
출처:https://stackoverflow.com/questions/171251/how-can-i-merge-properties-of-two-javascript-objects-dynamically
최근댓글