let array_A = [ {'id': 1, 'type': true}, {'id': 2, 'type': false}, {'id': 3, 'type': true}, {'id': 4, 'type': false}, {'id': 5, 'type': true}, ]; /** * 方法一: jQuery (若有使用 jQuery 可考慮) */ let array_B = $.extend(true, {}, array_A); // Convert object to array array_B = Object.values(array_B); /** * 方法二: JSON.parse(JSON.stringify()) * (純資料,可行;若遇 Function、Set、Map..等型態,失效) */ let array_B = JSON.parse(JSON.stringify(array_A)); /** * 方法三: 使用 lodash (library) */ let array_B = _.cloneDeep(array_A); /** * 方法四: 國外網友提供的遞迴方法,感覺很不錯 */ const clone = (items) => items.map(item => Array.isArray(item) ? clone(item) : {...item}); let array_B = clone(array_A); // Select type is true array_B = array_B.filter( number => number.type ); // Set type to false array_B.map( number => number.type = false ); console.log(array_A); console.log(array_B);
https://dev.to/samanthaming/how-to-deep-clone-an-array-in-javascript-3cig
https://kanboo.github.io/2018/01/27/JS-ShallowCopy-DeepCopy/