Home > Blockchain >  how to use the object variable inside string
how to use the object variable inside string

Time:05-04

I'm trying to create a string with a prefix variable which will dynamically allocate from the array of object but it shows UNDEFINED

this is my code

    app.post("/objectlooping",(req,res)=>{
    const myArray = [{"name":"venkat","number":"2345678900"}, {"name":"jhon","number":"2345678900"}, {"name":"selva","number":"2345678900"}];
    const message =`HI ${n}`;
myArray.forEach((element, index, array) => {
    var n=element.name;
    console.log(element.message); 
    
});
     
   });

can anyone help me to achieve this but this shows undefined

CodePudding user response:

If I understand this correctly you're trying to log a message for each name.

You can map over the objects in the array and return an array containing a message for each name in each object, and then join that array of messages up with a line break.

const myArray=[{name:"venkat",number:"2345678900"},{name:"jhon",number:"2345678900"},{name:"selva",number:"2345678900"}];

const message = myArray.map(obj => {
  return `Hi ${obj.name}`;
}).join('\n');

console.log(message);

CodePudding user response:

use message fn instead of variable then call it like

const message = (name)=>`Hi ${name}`
myArray.forEach((element, index, array) => {
    var name=element.name;
    console.log(message(name)); 
    
});
  • Related