I have a array as follows:
data = [
{
"tag":"A"
},
{
"tag":"B"
},
{
"tag":"C"
}
];
I want these tags' values in another array. I know I can do it using forEach
loop but want to do it in some other efficient way. Any way to do it?
CodePudding user response:
It's best to use a .map()
call for this instead of .forEach()
. See the MDN article for .map()
data = [
{
"tag":"A"
},
{
"tag":"B"
},
{
"tag":"C"
}
];
const tags = data.map(el => el.tag);
console.log(tags)
Rather than having to create a temporary array, the .map()
function transforms each value in an existing array into a new array. In this case, you just take the .tag
property of every old element to make the new element.