'how to use the object variable inside string
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
Solution 1:[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));
});
Solution 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);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
