将对象内容数组分配给新数组

Assign array of object content to a new array

我正在尝试将一个对象数组分配给另一个数组,但是当我创建新数组并在其他函数中更改它的值时,原始数组也会更改(这不正常)。我可以使用其他方法吗? 这是一个例子:http://codepen.io/Xiwi/pen/rLMbYp

看来您需要 copy/clone 数组,这样它就不会被引用更改。

如果数组中只有 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"}

对象本质上是引用。您必须创建一个新对象并分配另一个对象的值:

var test3 = [ Object.assign({}, test2[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]);