Skip to content
Advertisement

How to call the new data in JSON file for javascript

I want to retrieve the data for use again, how to use it?

example script

const data = { a: 1, b: 2, c: 3 }

function deleteData() {
    const newData = data
    for (let index = 0; index < 2; index++) {
        if (index === 1) {
            delete newData.a
        }
    }
}
deleteData()
console.log("old data: "+ data)
console.log("new data: "+ newData)

expected
old data: { a: 1, b: 2, c: 3 }
new data: { b: 2, c: 3 }

Advertisement

Answer

use Object.assign or spread syntax.

const data = { a: 1, b: 2, c: 3 }
const newData = Object.assign({}, data)    // or {...data}

function deleteData() {
    for (let index = 0; index < 2; index++) {
        if (index === 1) {
            delete newData.a
        }
    }
}
deleteData()
console.log("old data: ", data)
console.log("new data: ", newData)
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement