program story

여러 JavaScript 개체의 속성을 연결하는 방법

inputbox 2020. 9. 13. 10:30
반응형

여러 JavaScript 개체의 속성을 연결하는 방법


여러 JavaScript 개체 (연관 배열)를 "추가"하는 가장 좋은 방법을 찾고 있습니다.

예를 들면 다음과 같습니다.

a = { "one" : 1, "two" : 2 };
b = { "three" : 3 };
c = { "four" : 4, "five" : 5 };

계산하는 가장 좋은 방법은 무엇입니까?

{ "one" : 1, "two" : 2, "three" : 3, "four" : 4, "five" : 5 }

Object.assign()Javascript에서 기본적으로이를 달성하기 위해 ECMAscript 6이 도입 되었습니다.

Object.assign () 메소드는 대상체에 하나 이상의 소스 개체로부터 자신의 모든 열거 속성 값을 복사하는 데 사용된다. 대상 개체를 반환합니다.

Object.assign ()에 대한 MDN 문서

var o1 = { a: 1 };
var o2 = { b: 2 };
var o3 = { c: 3 };

var obj = Object.assign({}, o1, o2, o3);
console.log(obj); // { a: 1, b: 2, c: 3 }

Object.assign많은 최신 브라우저에서 지원 되지만 아직 전부는 아닙니다. BabelTraceur같은 변환기 를 사용하여 이전 버전과 호환되는 ES5 JavaScript를 생성하십시오.


jQuery 는이를 수행하는 좋은 방법이 있습니다.

http://api.jquery.com/jQuery.extend/


이렇게해야합니다.

function collect() {
  var ret = {};
  var len = arguments.length;
  for (var i=0; i<len; i++) {
    for (p in arguments[i]) {
      if (arguments[i].hasOwnProperty(p)) {
        ret[p] = arguments[i][p];
      }
    }
  }
  return ret;
}

입력:

a = { "one" : 1, "two" : 2 };
b = { "three" : 3 };
c = { "four" : 4, "five" : 5 };
d = collect(a, b, c);
console.log(d);

산출:

Object one=1 two=2  three=3 four=4 five=5

ECMAScript 6에는 확산 연산자가 있습니다. 이제 다음과 같이 할 수 있습니다.

const obj1 = {1: 11, 2: 22}
const obj2 = {3: 33, 4: 44}
const obj3 = {...obj1, ...obj2} 
console.log(obj3)

// {1: 11, 2: 22, 3: 33, 4: 44}

Underscore 에는이를 수행하는 방법이 거의 없습니다.

1. _.extend (대상, * 소스)

의 속성을 모두 복사 소스가 받는 개체 대상 객체 및 반환 대상 개체를.

_.extend(a, _.extend(b, c));
=> {"one" : 1, "two" : 2, "three" : 3, "four" : 4, "five" : 5 }

또는

_.extend(a, b);
=> {"one" : 1, "two" : 2, "three" : 3}
_.extend(a, c);
=> {"one" : 1, "two" : 2, "three" : 3, "four" : 4, "five" : 5 }

2. _.defaults (객체, * 기본값)

기입 정의 의 속성 객체 로부터 값을 디폴트 객체 및 반환 개체를 .

_.defaults(a, _.defaults(b, c));
=> {"one" : 1, "two" : 2, "three" : 3, "four" : 4, "five" : 5 }

또는

_.defaults(a, b);
=> {"one" : 1, "two" : 2, "three" : 3}
_.defaults(a, c);
=> {"one" : 1, "two" : 2, "three" : 3, "four" : 4, "five" : 5 }

함수가 3 개의 인수로 제한되어야하는 이유는 무엇입니까? 또한 hasOwnProperty.

function Collect() {
    var o={};
    for(var i=0;i<arguments.length;i++) {
      var arg=arguments[i];
      if(typeof arg != "object") continue;
      for(var p in arg) {
        if(arg.hasOwnProperty(p)) o[p] = arg[p];
      }
    }
    return o;
}

function Collect(a, b, c) {
    for (property in b)
        a[property] = b[property];

    for (property in c)
        a[property] = c[property];

    return a;
}

주의 : 이전 개체의 기존 속성을 덮어 씁니다.


Shallow-cloning (excluding prototype) or merging of objects is now possible using a shorter syntax than Object.assign().

Spread syntax for object literals was introduced in ECMAScript 2018):

const a = { "one": 1, "two": 2 };
const b = { "three": 3 };
const c = { "four": 4, "five": 5 };

const result = {...a, ...b, ...c};
// Object { "one": 1, "two": 2 , "three": 3, "four": 4, "five": 5 }

Spread (...) operator is supported in many modern browsers but not all of them.

So, it is recommend to use a transpiler like Babel to convert ECMAScript 2015+ code into a backwards compatible version of JavaScript in current and older browsers or environments.

This is the equivalent code Babel will generate for you:

"use strict";

var _extends = Object.assign || function(target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];
    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }
  return target;
};

var a = { "one": 1, "two": 2 };
var b = { "three": 3 };
var c = { "four": 4, "five": 5 };

var result = _extends({}, a, b, c);
// Object { "one": 1, "two": 2 , "three": 3, "four": 4, "five": 5 }

Probably, the fastest, efficient and more generic way is this (you can merge any number of objects and even copy to the first one ->assign):

function object_merge(){
    for (var i=1; i<arguments.length; i++)
       for (var a in arguments[i])
         arguments[0][a] = arguments[i][a];
   return arguments[0];
}

It also allows you to modify the first object as it passed by reference. If you don't want this but want to have a completely new object containing all properties, then you can pass {} as the first argument.

var object1={a:1,b:2};
var object2={c:3,d:4};
var object3={d:5,e:6};
var combined_object=object_merge(object1,object2,object3); 

combined_object and object1 both contain the properties of object1,object2,object3.

var object1={a:1,b:2};
var object2={c:3,d:4};
var object3={d:5,e:6};
var combined_object=object_merge({},object1,object2,object3); 

In this case, the combined_object contains the properties of object1,object2,object3 but object1 is not modified.

Check here: https://jsfiddle.net/ppwovxey/1/

Note: JavaScript objects are passed by reference.


Simplest: spread operators

var obj1 = {a: 1}
var obj2 = {b: 2}
var concat = { ...obj1, ...obj2 } // { a: 1, b: 2 }

ES6 ++

The question is adding various different objects into one.

let obj = {};
const obj1 = { foo: 'bar' };
const obj2 = { bar: 'foo' };
Object.assign(obj, obj1, obj2);
//output => {foo: 'bar', bar: 'foo'};

lets say you have one object with multiple keys that are objects:

let obj = {
  foo: { bar: 'foo' },
  bar: { foo: 'bar' }
}

this was the solution I found (still have to foreach :/)

let objAll = {};

Object.values(obj).forEach(o => {
  objAll = {...objAll, ...o};
});

By doing this we can dynamically add ALL object keys into one.

// Output => { bar: 'foo', foo: 'bar' }

function collect(a, b, c){
    var d = {};

    for(p in a){
        d[p] = a[p];
    }
    for(p in b){
        d[p] = b[p];
    }
    for(p in c){
        d[p] = c[p];
    }

    return d;
}

참고URL : https://stackoverflow.com/questions/2454295/how-to-concatenate-properties-from-multiple-javascript-objects

반응형