0

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

2
  • 1
    What do you expect it to return ? Since none of the elements have message key, accessing it via element.message returns undefined. Commented May 4, 2022 at 11:47
  • 2
    n doesn't exist when message is defined. Consider using console.log(`Hi ${element.name}`)? Commented May 4, 2022 at 11:47

2 Answers 2

2

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);

Sign up to request clarification or add additional context in comments.

Comments

1

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)); 
    
});

2 Comments

yes its works but instead of declaring {name} than ${name}
Good catch; edited.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.