删除数组对象也删除引用

时间:2019-10-06 04:00:57

标签: javascript arrays

在数组映射功能中,我试图复制一个对象并删除复制的资源对象。但是它同时删除了两个对象。

let array = [{
  'data': '1'
}, {
  'data': '2'
}];

array.map((val) => {
  val.temp = val.data;
  delete val.data;
});

在此过程中,将同时删除两个对象

我想删除数组中的数据对象并添加临时对象,

最终结果应为

array = [{
  'temp': '1'
}, {
  'temp': '2'
}];

1 个答案:

答案 0 :(得分:0)

在您的代码中,您不会像这样修改后$('#my-select').select2({ width: '300px', multiple: true, templateResult: function (item) { var $result = $('<span>'+item.text+'</span><input class="input" placeholder="Input Text Here" onclick="test()">'); return $result; }, templateSelection: function (item) { var $result = $('<span>'+item.text+'</span><input class="input" placeholder="Input Text Here" onclick="test()">'); return $result; } }).on("select2:selecting", function (e) { console.log("selecting",e.params.args.originalEvent); if (e.params.args.originalEvent.target.className === 'input') { e.preventDefault(); } } ); {@ 1}},

return

但是,如果您只想转换每个对象,使其键为val,则可以使用如下解构方法更优雅地做到这一点:

const array = [{'data': '1'}, {'data': '2'}];

const res = array.map((val) => {
  val.temp = val.data;
  delete val.data;
  return val; // required in the `.map()` callback to set the new value
});

console.log(res);