2016-06-20 3 views
2

다른 배열에 객체 배열을 지정하려고했지만 새 배열을 만들 때 다른 값을 변경하면 원래 배열이 변경됩니다. not ok). 다른 방법을 사용할 수 있습니까? 다음은 예제입니다. http : //codepen.io/Xiwi/pen/rLMbYp새 배열에 객체 내용 배열 할당

답변

3

참조로 변경되지 않도록 배열을 복사/복제해야합니다.

Primitive Types이 같이 할 수있는 배열에있는 경우 :

var test3 = JSON.parse(JSON.stringify(test2)); 

그렇지 않으면 재귀 솔루션 및 귀하의 질문에 구체적으로 필요합니다.

예 :

var test1 = [{name: 'test1'}]; 
 
var test2 = [{name: 'test2'}]; 
 
var test3 = JSON.parse(JSON.stringify(test2)); 
 

 
test3[0].name = 'test3'; 
 

 
// Open console 
 
console.log('Test2: ',test2[0]); // Object {name: "test2"} 
 
console.log('Test3: ',test3[0]); // Object {name: "test3"}

+0

'[] .splice (0,0, 편곡) '프리미티브 – kirinthos

+0

죄송합니다'[] .concat (편곡)' – kirinthos

+0

@kirinthos의 사본을 할 것입니다 아니. 당신도 똑같은 문제를 겪을 것입니다. 여기를 확인하십시오 : https://jsfiddle.net/jbL0vm9m/ – Sergio

0

객체가 기본적으로 참조입니다. 당신은 새로운 객체를 생성하고 다른 개체의 값을 할당해야합니다

var test3 = [ Object.assign({}, test2[0]) ]; 
0

를 사용하여 간단한 .map 다른 개체 중 하나 개 배열을 복사합니다. 내가 믿는 당신이 직렬화 필요가 없습니다

var test1 = [{name: 'test1'}]; 
var test2 = [{name: 'test2'}]; 
//var test3 = test2.slice(0); //doesn't work. objects are still references 
var test3 = test2.map(function(obj){ 
    //return obj; //doesn't work. objects are still references 
    var o={}; //create brand new object 
    for(var prop in obj) 
    o[prop]=obj[prop];//assign properties 
    return o;//works 
}); 

test3[0].name = 'test3'; 

// Open console 
console.log('Test2: ',test2[0]); 
console.log('Test3: ',test3[0]);