Home > OS >  how to change the name of a key in a object while destructuring
how to change the name of a key in a object while destructuring

Time:08-06

function splitWord(sql1) {
    let sql = sql1.split(" ")[0];
    let clo = sql1.split(" ")[1];
    return {sql , clo}
}

let {sql2 = sql , cl = clo} = splitWord("hello world!");
console.log(sql2 , cl)

the above function returns sql and clo in a object I want to change sql name to sql2 and clo name to cl while DE structuring how can I do it. I have tried it with equal but it is not working

CodePudding user response:

Its the other way around!, {[<original key>]:<new key>}

function splitWord(sql1) {
    let sql = sql1.split(" ")[0];
    let clo = sql1.split(" ")[1];
    return {sql , clo}
}

let {sql: sql2 , clo: cl} = splitWord("hello world!");
console.log(sql2 , cl)

CodePudding user response:

You can do it using an alias like this:

function splitWord(sql1) {
    let sql = sql1.split(" ")[0];
    let clo = sql1.split(" ")[1];
    return {sql , clo}
}

let {sql: sql2, clo: cl} = splitWord("hello world!");
console.log(sql2 , cl)

CodePudding user response:

Use ':' instead of '='.

let {sql2:sql,cl:clo}= splitWord("Hello World!").

This should achieve what you are asking.

CodePudding user response:

You can do the easy way as told by others. But answering to you question(Generalizing) :

function  updateObjectKeys(obj, oldKey, newKey){
    obj[newKey] = obj[oldKey]
    delete obj[oldKey]
}

let  wordSplit = {
    'sql' : 'hello'
}
console.log(wordSplit);
updateObjectKeys(wordSplit, 'sql','sql2')
console.log(wordSplit);

  • Related