[JS] Object.assign 合併物件
CityRay opened this issue · comments
RayLin commented
Object.assign 合併為一個新的物件,並建立新的 array
Method 1 (rest parameter)
// ES6
let state = {
todos: [{
id: 0,
completed: false,
text: 'Initial todo for demo purposes'
}]
}
let newObj = Object.assign({}, state, {
//建立一個新array,不會影響到原本的array
todos: [{
id: 1,
text: "new text",
completed: false
}, ...state.todos]
})
console.log(newObj)
console.log(state)
Method 2 (array concat)
let newObj = Object.assign({}, state)
//建立一個新array,不會影響到原本的array
newObj.todos = state.todos.concat({
id: 1,
text: "new text",
completed: false
})
console.log(newObj)
console.log(state)
Method 3 (array filter)
let state = {
todos: [{
id: 0,
completed: false,
text: 'Initial todo for demo purposes'
},
{
id: 1,
completed: false,
text: 'New Text2'
}]
}
let newObj = Object.assign({}, state)
//建立一個新array,不會影響到原本的array
newObj.todos = state.todos.filter((val) => val.id >= 0)
newObj.todos.push({id:3, text: 'new text3', completed: true})
console.log(newObj)
console.log(state)
refer