Home > OS >  How to get the key name dynamically from the list in Nodejs
How to get the key name dynamically from the list in Nodejs

Time:10-26

How to get the key name dynamically from the list and push it to an array using NodeJS.

This is my string { PRICE: '12', TYPE: 'Electronics' }

I want to push the key name PRICE, TYPE to an array like below:

const myArray = ["PRICE", "MyOrg::PRICE", "TYPE", "MyOrg::TYPE"]

I don't know how to get the key name dynamically from the list and push it to an array - can someone pls help me with this. Thanks.

Sample code:

const test = async () => {

        const myList =  { TYPE: '12', REGION: 'Electronics' }

        // Execpted array like below
        const myArray = ["PRICE", "MyOrg::PRICE", "TYPE", "MyOrg::TYPE"]


  };
  
  test();

CodePudding user response:

You could simply do Array.concat with Object.keys

const myList = { TYPE: '12', REGION: 'Electronics' };
let myArray = ['PRICE', 'MyOrg::PRICE'];

myArray = myArray.concat(Object.keys(myList));
console.log(myArray);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You just need variable substitution in your code, that you get by enclosing variable with curly braces like this ${variable}.

const myList =  { TYPE: '12', REGION: 'Electronics' }
array = Object.keys(myList)
myArray = []
for (let element of array){
    myArray.push(element, `MyOrg::${element}`)
}
console.log(myArray)
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Question doesn't really make sense. The following code generates the output that you are asking for, but it doesn't seem useful.

const myList = { "PRICE": 12, "TYPE": "Electronic" };

const myArray = [];

Object.keys(myList).forEach( function (key) {
    // Loop through all the keys
    myArray.push(key)
    myArray.push("MyOrg::" key)
})

console.log(myArray)
// Expected output
// myArray == ["PRICE", "MyOrg::PRICE", "TYPE", "MyOrg::TYPE"]
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related